Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Matt Joiner Avatar asked Feb 18 '10 05:02

Matt Joiner


People also ask

How do you send cookies in Python?

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.

How do I set-cookie in HTTP request?

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.

What is Cookiejar in Python?

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.

Are cookies sent in HTTP headers?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).


2 Answers

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()
        ...
like image 63
vlk Avatar answered Oct 21 '22 18:10

vlk


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...
like image 27
Tor Valamo Avatar answered Oct 21 '22 18:10

Tor Valamo