本文介绍了Python cookie未保存或以某种方式无法访问CGI脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这将有一个明显的答案...我一直在查看一堆Cookie的例子在Python中,并收集,正确的顺序来呈现东西是:获取cookie如果存在,设置cookie数据,打印内容类型头,输出cookie,然后打印一切。我已经建立在小部分,我不能告诉什么是使这个版本不工作。它创建一个cookie(一个数字字符串,只要我在Firefox / Chrome中可以看到),但它似乎没有创建UID,所以当另一个脚本尝试使用UID时,它会创建一个错误。

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

我尝试做

c = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))
uid = c.get("uid")

是我真正想做的),uid返回为None。

here (or in another script in the same directory, which is what I actually want to do), uid gets returned as None.

推荐答案

您正在创建cookie对象,然后运行重定向代码路径,而不设置cookie。

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.

这篇关于Python cookie未保存或以某种方式无法访问CGI脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:36