简体   繁体   中英

Sending “Set-Cookie” in a Python HTTP server

How do I send the "Set-Cookie" header when working with a BaseHTTPServerRequestHandler , and Cookie ? BaseCookie and children don't provide a method to output the value to be passed into send_header() , and *Cookie.output() does not provide a HTTP line delimiter.

Which Cookie class should I be using? Two have survived into Python3, what are the differences?

This sends a Set-Cookie header for every 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()
        ...

Use C = http.cookie.SimpleCookie to hold the cookies and then C.output() to create the headers for it.

Example here

The request handler has a wfile attribute, which is the socket.

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...

I've used the code below, which uses SimpleCookie from http.cookies to produce an object for a cookie. Then, I add a value to it, and finally, I add it to the list of headers to send (as a Set-Cookie field) with the usual 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'))

The parameters for cookie.output are important:

  • header='' ensures that no header is added to the string it produces (if not done, it will produce a string that will start with Set-Cookie: , which will cause to strings like that in the same header, since send_header will add its own).
  • sep='' causes no final separator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM