Python cookie未保存或无法被CGI脚本访问

0 投票
1 回答
568 浏览
提问于 2025-04-16 08:33

我觉得这个问题的答案应该很明显……我看了很多关于Python中cookie的例子,了解到正确的步骤是:先检查cookie是否存在,如果存在就获取它,然后设置cookie的数据,接着打印内容类型的头部,输出cookie,最后再打印其他内容。我是一步步搭建这个过程的,但我不知道为什么这个版本不工作。它确实创建了一个cookie(在Firefox/Chrome中看到的是一串数字),但是似乎没有生成UID,所以当另一个脚本尝试使用这个UID时,就会出现错误。

下面是关键部分,省略了一些导入(看起来都没问题)、数据库连接等:

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。

1 个回答

0

我觉得你可能是眼睛疲劳了。你在创建cookie对象后,接着执行了"redirect"这段代码,但这段代码并没有设置cookie。

撰写回答