0

ユーザー名とパスワードを取得して、データベース内の値でユーザー名とパスワードを検証する別の python スクリプトに渡したいログイン python スクリプトがあります。ユーザーが存在する場合は、Cookie に設定されたユーザー名の値を使用して Cookie を作成し、次のページにリダイレクトします。存在しない場合は、前のページに戻します。

これは私のindex.pyコードです:

#!/usr/bin/python
import cgi;
import cgitb;
import sqlite3;
import os;
import Cookie;
import sys;



cgitb.enable()
form= cgi.FieldStorage()
username= None
userID = None
userPW= None

#Open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()





def createdb():
    ###Create table login
    conn.execute(""" CREATE TABLE login (userid INTEGER PRIMARY KEY ,
    username TEXT, passwrd TEXT)""")
    ##
    ###Create table excursion
    conn.execute(""" CREATE TABLE excursion (excurid INTEGER PRIMARY KEY,
    location TEXT, excurDate TEXT, excurTime TEXT, user INTEGER, FOREIGN KEY(user) REFERENCES login(userid))""")
    ##
    #Create table sighting
    conn.execute(""" CREATE TABLE sighting (sightid INTEGER PRIMARY KEY,
    species TEXT, observation TEXT, loginuser INTEGER, userexcursion INTEGER, FOREIGN KEY(loginuser, userexcursion) REFERENCES excursion (user, excurid))""")
    ##
    #Insert username and password in login table
    conn.execute("""INSERT INTO login (userid,username,passwrd) VALUES(NULL,'Diego','diego')""")
    conn.commit()

    #Insert dummy data in excursion table
    conn.execute("""INSERT INTO excursion (excurid,location,excurDate,excurTime,user) VALUES(NULL,'Macquarie','04/01/2012','6:00pm',1)""")
    conn.execute("""INSERT INTO excursion (excurid,location,excurDate,excurTime,user) VALUES(NULL,'Carlton','04/05/2012','7:00am',1)""")
    conn.commit()

    #Insert dummy data in sighting table
    conn.execute("""INSERT INTO sighting (sightid,species,observation,loginuser,userexcursion) VALUES(NULL,'Duck','long beak',1,1)""")
    conn.execute("""INSERT INTO sighting (sightid,species,observation,loginuser,userexcursion) VALUES(NULL,'Parrots','beautiful and colorful',1,2)""")
    conn.commit()
    conn.close()       



if not os.path.exists("manager.db"):
    createdb();

#define start of page
pagehead1= """
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
        <title> Home </title>
        <link rel='stylesheet' type='text/css' href='/index.css/'/>
    </head>

    <body>
"""

pagehead2="""

        <form method=POST action="http://localhost:8000/cgi-bin/validate.py">
            <div id="container">
                <div id="header">
                    <h1> Field Note Manager </h1>
                    <p class= "description"> Observe...Record...Save! </p>
                </div>

                <div id="wrapper">
                    <div id="content">
                        <p> Username: <input type="text" name="usernameLogin"/> </p>
                        <br/>
                        <p> Password: <input type="password" name="passwordLogin"/> </p>
                        <br/>
                        <p id="login"> <input type="submit" name="loginBtn" value="Login"/> </p>
                    </div>
                </div>

                <div id="footer">
                    <p> Copyright 42578647, 2012 </p>
                </div>
            </div>
    """

pagefoot= """ </form>
                  </body>
                  </html> """

print "Content_type: text/html\n\n"
print pagehead1
print pagehead2
print pagefoot

これは、データベースでユーザー名を検証するための私のコードです:

#! usr/local/bin/python
import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

username= None
form= cgi.FieldStorage()

UserPW= [form.getvalue('usernameLogin'), form.getvalue('passwordLogin')]
isValidate = validate(UserPW);

if isValidate == 1:
    print "Content_type: text/html\n\n"
    print """
    <html>
        <head> Redirecting </head>
        <body>
            <form method= POST action="http://localhost:8000/cgi-bin/page1.py">
            <p> Validated! <input type="submit" value="Enter"/> </p>
            </form>
        </body>
    </html> """
elif isValidate == 0:
    print "Content_type: text/html\n\n"
    print """
    <html>
        <head> Redirecting </head>
        <body>
            <form method=POST action= "http://localhost:8000/cgi-bin/index.py">
                <p> Username or Password incorrect! <input type="submit" value="Go back"/> </p>
            </form>
        </body>
    </html>
    """



def validate(UserPW):
    sql= "SELECT * FROM login"
    userPWDatabase=cur.execute(sql)
    cur.fetchall()
    for record in userPWDatabase:
        if record == UserPW:
            #Create cookie
            C= Cookie.SimpleCookie()
            #take the value of the index.py form variable username
            username= form.getvalue('usernameLogin')
            #set the cookie with the usernameLogin key
            C['usernameLogin']= username
            print C
            return 1
        else:
            return 0              

どこに問題があるのか​​わからない

4

4 に答える 4

1

「問題がどこにあるのかわからない」よりも詳細を教えてください。正確には何が起こっているのか、何かある場合はどのログメッセージが表示されるのか。

呼び出される前に「検証」関数定義を移動しようとしましたか?これはあなたの問題の一部かもしれないと思います。


更新:いくつかの調査といくつかの修正の後、私はそれを機能させました:

  1. 前に述べたように、「検証」関数の定義は、呼び出される前に設定する必要があります
  2. 「SELECT*FROM login」は3つのフィールド(id、username、passwrd)を返すため、SQLクエリが正しくないため、「SELECT username、passwrdFROMlogin」に変更する必要があります。
  3. sqliteによって返されるレコードはタプルであり、リストと比較しようとしているため、TYPEの不一致があります。次のように変更する場合の1つの解決策: "if list(record)== UserPW:"

また、ubuntuの下で/var/log/apache2/error.logを見ると非常に役立ちます。

最終的に次のことにつながりました:

#!/usr/bin/env python

import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

username= None
form= cgi.FieldStorage()


def validate(UserPW):
      sql= "SELECT username,passwrd FROM login;"
      cur.execute(sql)
      userPWDatabase=cur.fetchall()
      for record in userPWDatabase:
          if list(record) == UserPW:
              #Create cookie
              C= Cookie.SimpleCookie()
              #take the value of the index.py form variable username
              username= form.getvalue('usernameLogin')
              #set the cookie with the usernameLogin key
              C['usernameLogin']= username
              print C
              return 1
          else:
              return 0              



UserPW= [form.getvalue('usernameLogin'), form.getvalue('passwordLogin')]
isValidate = validate(UserPW);

if isValidate == 1:
      print "Content-type: text/html\n\n"
      print """
      <html>
          <head> Redirecting </head>
          <body>
              <form method= POST action="http://localhost:8000/cgi-bin/page1.py">
              <p> Validated! <input type="submit" value="Enter"/> </p>
              </form>
          </body>
      </html> """
elif isValidate == 0:
      print "Content-type: text/html\n\n"
      print """
      <html>
          <head> Redirecting </head>
          <body>
              <form method=POST action= "http://localhost:8000/cgi-bin/index.py">
                  <p> Username or Password incorrect! <input type="submit" value="Go back"/> </p>
              </form>
          </body>
      </html>
      """
于 2012-04-24T09:01:56.253 に答える
0

Set-Cookieヘッダーのものが行の前にあると想定されていることを読んだだけです:

print "Content_type: text/html\n\n"

そのため、コードを再度修正しましたが、正常に機能しています。ユーザー名/パスワードが間違っている場合は前のスクリプトに戻り、検証後に次のスクリプトに進みます。最終的なコードは次のとおりです。

#! usr/local/bin/python
import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

cgitb.enable()
username= None
form= cgi.FieldStorage()

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

pagehead= """
    <html>
        <head> Redirecting </head>
        <body>

            """
pagefoot="""<form method= POST action="http://localhost:8000/cgi-bin/page1.py">
            <p> Validated! <input type="submit" value="Enter"/> </p>
            </form>
        </body>
    </html> """
errorpagefoot= """
<form action="http://localhost:8000/cgi-bin/index.py">
<p> Error! <input type="submit" value="Go Back"/> </p>
</form>
</body>
</html>"""


userName= form.getvalue('usernameLogin')
userPW= form.getvalue('passwordLogin')
userPWDatabase = conn.execute("SELECT username,passwrd FROM login WHERE username=? and passwrd=?",[userName,userPW])
cur.fetchone()
for result in userPWDatabase:
    userDb= result[0]
    pwDb= result[1]
    if userDb == userName and pwDb == userPW:
        #Create Cookie
        C= Cookie.SimpleCookie()
        #take the value of usernameLogin into the variable username
        username= form.getvalue('usernameLogin')
        #Set-Cookie header with the usernameLogin key
        C['usernameLogin'] = username
        print C
    elif userDb != userName and pwDb != userPW:
        print errorpagefoot

print "Content_type: text/html\n\n"
print pagehead
if username:
    print pagefoot
else:
    print errorpagefoot

@アレクシス

お時間をいただきありがとうございます。Alexisを助けてください:)

于 2012-04-25T12:16:17.403 に答える
0

コード validate.py を次のように変更しました。

  #! usr/local/bin/python
import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

cgitb.enable()
username= None
form= cgi.FieldStorage()

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

pagehead= """
    <html>
        <head> Redirecting </head>
        <body>

            """
pagefoot="""<form method= POST action="http://localhost:8000/cgi-bin/page1.py">
            <p> Validated! <input type="submit" value="Enter"/> </p>
            </form>
        </body>
    </html> """
errorpagefoot= """
<form action="http://localhost:8000/cgi-bin/index.py">
<p> Error! <input type="submit" value="Go Back"/> </p>
</form>
</body>
</html>"""


print "Content_type: text/html\n\n"
print pagehead
userName= form.getvalue('usernameLogin')
userPW= form.getvalue('passwordLogin')
userPWDatabase = conn.execute("SELECT username,passwrd FROM login WHERE username=? and passwrd=?",[userName,userPW])
cur.fetchone()
for result in userPWDatabase:
    userDb= result[0]
    pwDb= result[1]
    if userDb == userName and pwDb == userPW:
        #Create Cookie
        C= Cookie.SimpleCookie()
        #take the value of usernameLogin into the variable username
        username= form.getvalue('usernameLogin')
        #Set-Cookie header with the usernameLogin key
        C['usernameLogin'] = username
        print C
        print pagefoot    
    elif userDb != userName and pwDb != userPW:
        print errorpagefoot

現在は機能していますが、ユーザー名またはパスワードが正しくない場合、前のページにリダイレクトされなくなりました

于 2012-04-25T09:22:14.600 に答える
0

わかりました、新しいコードを読んだ後、まだいくつかのバグがあるようですが、主なエラーはログイン/パスワードをチェックしようとする方法だと思います: 最初にデータベースからユーザー名とパスワードをフィルタリングして選択します。ログインがデータベースのプライマリであるため、1または0の結果のみを返し、結果をループして、ユーザー名とパスワードが両方とも正しいか、または両方が間違っているかを確認しようとします。その結果、ユーザー名が正しいが、パスワードではありません(および逆)。したがって、コードの最後の部分を次のように変更することをお勧めします。

print "Content-type: text/html\n\n"
print pagehead
userName= form.getvalue('usernameLogin')
userPW= form.getvalue('passwordLogin')
cur.execute("SELECT username,passwrd FROM login WHERE username=?",[userName])
userPWDatabase = cur.fetchone()
if userPWDatabase is not None:
        userDb= userPWDatabase[0]
        pwDb= userPWDatabase[1]
        #Create Cookie
        C= Cookie.SimpleCookie()
        #take the value of usernameLogin into the variable username
        username= form.getvalue('usernameLogin')
        #Set-Cookie header with the usernameLogin key
        C['usernameLogin'] = username
        print C
        print pagefoot    
else:
        print errorpagefoot

ユーザー名とパスワードのフィルターを使用して SQL クエリを保持することもできますが、他に何もチェックする必要がないことに注意してください。

さらに、あなたの目的が何なのか (cgi-bin/python を学ぶためか、実際のアプリケーションをセットアップするためか) はわかりませんが、Django ( www.djangoproject.com )に興味があるかもしれません。

于 2012-04-25T12:02:28.237 に答える