create a http server and parse cookies and return a json response in python

To create a http server in python, you can use the built-in http.server module. Here's an example of how to create a server and parse cookies:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import urllib.parse

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # parse cookies
        if 'Cookie' in self.headers:
            cookie_string = self.headers['Cookie']
            cookies = dict(urllib.parse.parse_qsl(cookie_string, keep_blank_values=True))
        else:
            cookies = {}

        # create json response
        response = {
            'message': 'Hello World!',
            'cookies': cookies
        }
        response_bytes = json.dumps(response).encode('utf-8')

        # send headers
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', len(response_bytes))
        self.send_header('Set-Cookie', 'mycookie=test')
        self.end_headers()

        # send response
        self.wfile.write(response_bytes)

def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print('Starting httpd on port %d...' % port)
    httpd.serve_forever()

if __name__ == "__main__":
    run()
1203 chars
39 lines

In this example, we defined a RequestHandler class which inherits from the BaseHTTPRequestHandler provided by http.server. When a GET request is made to the server, the do_GET method is called. Inside do_GET, we check if the request contains any cookies, and if it does, we parse them into a dictionary.

Next, we create a response dictionary containing our JSON message and the cookies received in the request. We serialize this dictionary into bytes using json.dumps, and send it back to the client as the response.

Before sending the response, we set the Content-Type header to application/json to indicate that the response is JSON. We also set the Content-Length header to the length of our response bytes, and set a Set-Cookie header to create a cookie named mycookie with the value test.

Finally, we call self.wfile.write(response_bytes) to send the response body back to the client.

To run the server, simply execute python server.py in your terminal. The server will start on port 8000 by default. You can test the server and see the JSON response by visiting http://localhost:8000 in your web browser or using a tool like curl.

related categories

gistlibby LogSnag