create a http server and parse cookies in python

You can create a simple HTTP server and parse cookies in Python by using the built-in http.server module. Here's an example:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.cookies import SimpleCookie

class MyHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        
        # Parse cookies
        cookies = SimpleCookie(self.headers.get('Cookie'))
        name = cookies.get('name').value if 'name' in cookies else 'anonymous'
        
        self.end_headers()
        self.wfile.write(f'Hello, {name}!'.encode())

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, MyHTTPRequestHandler)
    print('HTTP server started')
    httpd.serve_forever()
699 chars
22 lines

In this code, we define a custom MyHTTPRequestHandler class which extends BaseHTTPRequestHandler. It overrides the do_GET() method, which is called for every GET request received by the server. Inside do_GET(), we:

  1. Send a 200 OK response.
  2. Parse the Cookie header using the SimpleCookie class from the http.cookies module.
  3. Extract the value of the name cookie, or use 'anonymous' if the cookie is not present.
  4. Send the response body containing a personalized greeting.

To run this server, save the code in a file named server.py, and execute it with Python:

main.py
$ python server.py
19 chars
2 lines

Then open a browser and go to http://localhost:8000. You should see a greeting message with your name, if you have a name cookie set. If you don't have a name cookie set, the message will say "Hello, anonymous!".

gistlibby LogSnag