Python cookie is either not saved or somehow not accessible to CGI script
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开发者_如何学C'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\nContent-Type: text/html\n\n")
else:
print("Content-Type: text/html")
print c.output()
print("\n\n")
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.
I think you just had tired eyes. You're creating the cookie object and then you're running the "redirect"
codepath, which doesn't set the cookie.
精彩评论