我有一个登录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
我不知道问题在哪里
答案 0 :(得分:1)
请您提供更多详细信息,而不是“我不知道问题出在哪里”:究竟会发生什么,如果有的话,您会得到什么日志消息。
您是否尝试在调用之前移动“验证”函数定义?我认为这可能是你问题的一部分。
更新:经过一些调查和一些修复,我得到了它的工作:
另外,在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>
"""
答案 1 :(得分: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
它现在正在运行,但它不再重定向到上一页,因为用户名或密码不正确
答案 2 :(得分: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)
答案 3 :(得分: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
感谢您的时间和帮助Alexis:)