我有以下脚本,我正在努力工作,所以我会调整它到我的网站:
#!/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变量中的cookie已设置,但是当我刷新页面时,它不会显示先前设置的cookie。好像它没有存储。没有错误日志,只有页面没有与我的Web浏览器一起存储数据。
答案 0 :(得分: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>'