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. 您的 sql 查询不正确,因为“SELECT * FROM login”将返回 3 个字段(id、username 和 passwrd),因此您应该将其更改为“SELECT username,passwrd FROM login”
  3. sqlite 返回的记录是一个元组,并且您正在尝试将其与列表进行比较,因此存在 TYPE 不匹配。一种解决方案是否更改为:“如果列表(记录)== 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

我将代码 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 回答
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

@亚历克西斯

感谢您的时间和帮助亚历克西斯 :)

于 2012-04-25T12:16:17.403 回答