将python脚本重定向到另一个python脚本以验证登录凭据

2024-09-27 21:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个登录python脚本,在该脚本中,我希望获取用户名和密码,并将其传递给另一个python脚本,该脚本使用数据库中的值验证用户名和密码。如果用户存在,它将使用cookie中设置的用户名值创建一个cookie并重定向到下一个页面,否则,它将返回到上一个页面。在

这是我的索引.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

这是我在数据库中验证用户名的代码:

^{pr2}$

我不知道问题出在哪里


Tags: keytextimportdividexecutetablelogin
3条回答

我改了密码验证.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

它现在可以工作,但不会再重定向到上一页,以防用户名或密码不正确

好的,在阅读了你的新代码之后,你似乎仍然有几个错误,但是我认为主要的错误是你试图检查登录名/密码的方式:首先你从数据库中选择它,通过对用户名和密码进行过滤,这只能返回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

你能提供比“我不知道问题出在哪里”更详细的信息吗?具体发生了什么,如果有一些日志消息,你会收到什么消息。在

您是否尝试在调用“validate”函数定义之前移动它?我想这可能是你问题的一部分。在


更新:经过一些调查和一些修复,我得到了它的工作:

  1. 如前所述,“validate”函数定义应该在调用之前设置
  2. 您的sql查询不正确,因为“SELECT*FROM login”将返回3个字段(id、username和passwrd),因此您应该将其更改为“SELECT username,passwrd FROM login”
  3. sqlite返回的记录是一个元组,您试图将其与列表兼容,因此存在类型不匹配。一个解决方案if改为:“if list(record)==UserPW:”

另外,在ubuntu下查看/var/log/apache2/错误.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>
      """

相关问题 更多 >

    热门问题