Python Cookies未设置

0 投票
1 回答
1929 浏览
提问于 2025-04-18 08:02

我有一个脚本,想让它正常工作,然后再把它调整到我的网站上。

#!/usr/bin/python
print "Content-type: text/html\n\n"
import sha, time, Cookie, os
cookie = Cookie.SimpleCookie()
existent = os.environ.get('HTTP_COOKIE')

# If new session
if not existent:
# The sid will be a hash of the server time
    sid = sha.new(repr(time.time())).hexdigest()
# Set the sid in the cookie
    cookie['sid'] = sid
# Will expire in a year
    cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60
# If already existent session
    print '<p>New session</p>'

    print '<p>SID =', cookie['sid'], '</p>'
    print '</body></html>'

else:
    cookie.load(existent)
    sid = cookie['sid'].value
    print cookie
    print '<html><body>'
    print '<p>Already existent session</p>'
    print '</body></html>'

但是不知道为什么,虽然在cookie变量中设置了cookies,但当我刷新页面时,之前设置的cookie却不见了。看起来好像没有被保存。没有错误日志,只是我的网页浏览器没有存储这些数据。

1 个回答

0

你需要把一个 Set-Cookie 头信息发送回浏览器;你只是创建了cookie数据,但并没有把它发送回去。

首先,不要马上发送一整套的头信息;你需要加入一个新的 Set-Cookie 头信息:

print "Content-type: text/html"

这样做只会打印出 仅仅是 Content-Type 头信息,没有发送额外的换行。

接下来,当你想把cookie发送回浏览器时,你需要 打印 这个cookie;打印cookie会生成一个有效的 Set-Cookie 头信息,然后再用一个额外的换行结束头信息:

print cookie
print  # end of headers

完整的代码如下:

print "Content-type: text/html"

import sha, time, Cookie, os
cookie = Cookie.SimpleCookie()
existent = os.environ.get('HTTP_COOKIE')

# If new session
if not existent:
    # The sid will be a hash of the server time
    sid = sha.new(repr(time.time())).hexdigest()
    # Set the sid in the cookie
    cookie['sid'] = sid
    # Will expire in a year
    cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60
    # print new cookie header
    print cookie
    print

    print '<html><body>'
    print '<p>New session</p>'    
    print '<p>SID =', cookie['sid'], '</p>'
    print '</body></html>'

else:
    # If already existent session  
    cookie.load(existent)
    sid = cookie['sid'].value
    print cookie
    print

    print '<html><body>'
    print '<p>Already existent session</p>'
    print '</body></html>'

撰写回答