将cookie与Python CGI一起添加到网页中



我正在尝试使用python的cookie将cookie添加到网页上,所以我有:

def cookie():
   #create cookie1 and cookie2 here using Cookie.SimpleCookie()
   print cookie1
   print cookie2

print "Content-Type: text/html"
print
cookie()
try:
    cookie= Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
    user= cookie["user"].value
    print user
except (Cookie.CookieError, KeyError):
    print 'no cookie'
page= open('example.html', 'r').read()
print page

现在问题是cookie1和cookie2在页面本身中打印出来,在运行脚本时可以看到。因此,没有保存cookie,除了打印以外的"否饼干"。我在做什么错?

1-您的代码没有意义。cookie1和cookie2在第一个功能中未定义。

2-看起来您正在尝试使用旧的CGI库打印东西,在该库中使用标题,空白行,然后是页面内容。cookies还通过Web服务器作为HTTP标头发送,并通过浏览器将其作为HTTP标头发送。它们没有出现在网页上。因此,您需要在空白行之前拥有" set-cookie"数据。

除非您必须使用CGI模块,否则我会研究其他解决方案。CGI基本上已经死了 - 这是一个旧的,有限的,标准的;配置服务器可能是一个巨大的麻烦。表演从来都不出色。还有更好的选择。

大多数(如果不是全部)使用Python使用WSGI协议的现代Web开发。(Python Web Frameworks,WSGI和CGI如何融合在一起,http://www.python.org/dev/peps/peps/pep-0333/)

烧瓶和瓶子是两个非常简单的WSGI框架。(Pryamid和Django是两个先进的)。除了大量非常重要的功能外,它们还可以轻松地指定HTML响应和与之相同的HTTP标头(包括cookie),然后框架将有效载荷传递到服务器。这个

http://flask.pocoo.org/docs/quickstart/

http://bottlepy.org/docs/dev/tutorial.html

如果我必须使用CGI,我可能会做这样的事情:(伪代码)

def setup_cookie():
    # try/except to read the cookie
    return cookie
def headers(cookie):
    # print a set-cookie header if needed
    return "SetCookie: etc"
def page_content(cookie):
    # maybe you want to alter the page content with a regex or something based on the cookie value
    return html
cookie = setup_cookie()
print headers( cookie )
print ""
print page_content( cookie )

请记住 - 使用旧的CGI标准,您可以打印出比HTML的标题 - 这意味着,如果您的内容生成会影响标题值(如Cookie),则需要能够在"打印"之前覆盖该标题。

最新更新