Python cookie is either not saved or somehow not accessible to CGI script

我与影子孤独终老i 提交于 2019-12-13 05:41:58

问题


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\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.


回答1:


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.



来源:https://stackoverflow.com/questions/4446313/python-cookie-is-either-not-saved-or-somehow-not-accessible-to-cgi-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!