Sending "Set-Cookie" in a Python HTTP server

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.