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?
To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.
To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.
cookiejar module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data – cookies – to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests.
Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With