Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

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'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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...