在Python HTTP服务器中发送“Set-Cookie”

11

如何在使用 BaseHTTPServerRequestHandlerCookie 时发送“Set-Cookie”标头? BaseCookie 及其子类不提供将值输出到传递到 send_header() 的方法,而 *Cookie.output() 不提供 HTTP 行分隔符。

我应该使用哪个 Cookie 类?有两种在 Python3 中仍然存在,它们有什么区别?

3个回答

6

这将为每个Cookie发送一个Set-Cookie头

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")

        cookie = http.cookies.SimpleCookie()
        cookie['a_cookie'] = "Cookie_Value"
        cookie['b_cookie'] = "Cookie_Value2"

        for morsel in cookie.values():
            self.send_header("Set-Cookie", morsel.OutputString())

        self.end_headers()
        ...

2
这个答案应该被接受。其他的不完整。 - dmitri

3
使用C = http.cookie.SimpleCookie来保存cookie,然后使用C.output()来创建相应的标头。 这里有示例 请求处理程序有一个wfile属性,它是套接字。
req_handler.send_response(200, 'OK')
req_handler.wfile.write(C.output()) # you may need to .encode() the C.output()
req_handler.end_headers()
#write body...

@Tor 这个发送不起作用,SimpleCookie 没有输出完整的头部。 - Matt Joiner
1
不,cookie的输出既不能写入处理程序中的self.wfile,也不能写入self.send_header() - Matt Joiner
@Tor。我知道你给出的例子“看起来”是正确的,但如果你实际尝试一下,你就会明白我在说什么了。 - Matt Joiner
1
self.send_header('Set-Cookie', C.output(header='')) 可以使用。从这里得到的。 http://b.leppoc.net/2010/02/12/simple-webserver-in-python/很烦人的是,这在 http.server.html 或 http.cookies.html 的 Python 文档中都没有记录。 - Shanness
您还可以使用flush_headers()清空头缓冲区。 - Max Matti
显示剩余3条评论

1
我使用了下面的代码,它使用来自http.cookiesSimpleCookie来生成一个cookie对象。然后,我添加了一个值,并最终将其添加到要发送的标题列表中(作为Set-Cookie字段),并使用通常的send_header发送:
    def do_GET(self):

        self.send_response(200)
        self.send_header("Content-type", "text/html")

        cookie = http.cookies.SimpleCookie()
        cookie['a_cookie'] = "Cookie_Value"
        self.send_header("Set-Cookie", cookie.output(header='', sep=''))

        self.end_headers()
        self.wfile.write(bytes(PAGE, 'utf-8'))

cookie.output 的参数非常重要:

  • header='' 确保不向生成的字符串添加任何标头(如果不这样做,它将生成一个以 Set-Cookie: 开头的字符串,这会导致在同一标头中有多个类似的字符串,因为 send_header 会添加自己的标头)。
  • sep='' 不会产生最终分隔符。

1
只有在同一时间只写入一个 cookie 的情况下,这才能正常工作。 - vlk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接