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

11 投票
3 回答
13115 浏览
提问于 2025-04-15 19:25

我该如何在使用 BaseHTTPServerRequestHandlerCookie 时发送 "Set-Cookie" 这个头信息呢?BaseCookie 及其子类并没有提供一个方法来输出可以传给 send_header() 的值,而 *Cookie.output() 也没有提供一个 HTTP 行分隔符。

我应该使用哪个 Cookie 类呢?有两个类在 Python3 中还在用,它们有什么区别?

3 个回答

1

我使用了下面的代码,这段代码利用了来自http.cookiesSimpleCookie来创建一个cookie对象。接着,我给这个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=''这个设置让生成的字符串后面没有任何分隔符。
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()
        ...
3

使用 C = http.cookie.SimpleCookie 来保存 cookies,然后用 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...

撰写回答