【问题标题】:Sending "Set-Cookie" in a Python HTTP server在 Python HTTP 服务器中发送“Set-Cookie”
【发布时间】:2020-07-30 01:24:27
【问题描述】:

使用BaseHTTPServerRequestHandlerCookie 时如何发送“Set-Cookie”标头? BaseCookie 和子级不提供输出要传递给 send_header() 的值的方法,*Cookie.output() 不提供 HTTP 行分隔符。

我应该使用哪个Cookie 类?两个都活到了 Python3,有什么区别?

【问题讨论】:

    标签: python http cookies


    【解决方案1】:

    这会为每个 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】:

    使用C = http.cookie.SimpleCookie 保存cookie,然后使用C.output() 为其创建标头。

    Example here

    请求处理程序有一个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 没有输出完整的 header
    • 当然你需要添加更多的标题,而不仅仅是 cookie...我认为这很明显。
    • 不,cookie 的输出不能写入处理程序中的self.wfile self.send_header()
    • @Tor。我知道你给出的例子看起来是对的,但如果你真的尝试一下,你就会明白我在说什么。
    • self.send_header('Set-Cookie', C.output(header='')) 有效。从这里得到它。 b.leppoc.net/2010/02/12/simple-webserver-in-python 烦人的这在 http.server.html 或 http.cookies.html python 文档中都没有记录..
    【解决方案3】:

    我使用了下面的代码,它使用了SimpleCookiehttp.cookies 生成一个cookie 对象。 然后,我为其添加一个值,最后,我将其添加到标题列表中 使用通常的send_header 发送(作为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"
            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='' 导致没有最终分隔符。

    【讨论】:

    • 这只有在一次只写入一个 cookie 时才有效
    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 2021-09-15
    • 2011-07-27
    • 2016-10-15
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多