I think this is going to have an obvious answer... I've been looking at a bunch of examples of cookies in Python and have gathered that the proper order to present things is: get the cookie if it exists, set cookie data, print the content type header, output the cookie, and then print everything else. I've built this up in small parts and I can't tell what's making this version not work. It does create a cookie (with a string of numbers, as far as I can see in Firefox/Chrome) but it doesn't seem to create the UID, so that when another script tries to use the UID, it create an error.
Here's the meat of it, skipping imports (all seem to be okay), database connector, etc.:
c = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))
mode = "first"
when = c.get("lastvisit")
if when is None:
if form.has_key("username") and form.has_key("passwd"):
username = form['username'].value
cursor.execute('SELECT passwd, uid FROM user WHERE username="%s"' % (username))
person = cursor.fetchall()[0]
check = person[0]
if check == md5.new(form['passwd'].value).hexdigest():
c = Cookie.SimpleCookie()
c["lastvisit"] = str(time.time())
c["uid"] = person[1]
mode = "redirect"
else: # reload login page with error message
mode = "tryagain"
else: # go to first login form
mode = "first"
else: # was already logged in
mode = "redirect"
if mode == "redirect":
print("Location:http://somewhere.com
Content-Type: text/html
")
else:
print("Content-Type: text/html")
print c.output()
print("
")
if mode == "first":
print("<h2>Please log in</h2>")
elif mode == "tryagain":
print("<h2>Please try again</h2>")
print('<form method=POST action="self.cgi">Username: <input type=textarea name="username">Password: <input type=password name="passwd"><input type=submit value="Submit">')
If I try to do
c = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))
uid = c.get("uid")
here (or in another script in the same directory, which is what I actually want to do), uid gets returned as None.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…