Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Python simple http server

30 Mar 2025 »

https://github.com/michalmuchakr/lab_1/blob/a55de82ce6c83ab6950994cd4f6ce679f3fa95ef/python_server/server.py#L58

import json
from http.server import BaseHTTPRequestHandler, HTTPServer
#import urlparser.parse
import traceback


class SimpleRequestHandler(BaseHTTPRequestHandler):

    def do_OPTIONS(self):
        self.send_response(200, "OK")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()

    def getPathParams(self):
        path = "/"    
        params = {}
        post = {}

        try:
            if "?" in self.path:
                params = self.path.split("?")[1]
                params = dict([
                    e.split("=")
                    for e in params.split("&")
                ])
        except:
            traceback.print_exc()

        return path, params

    def getPost(self):
        content_length: int = int(self.headers['Content-Length'])
        post = {}
        if content_length > 0:
            post_data: bytes = self.rfile.read(content_length)
            received_data: dict = json.loads(post_data.decode())
            post = received_data
        return post

    def do_GET(self) -> None:
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()

        path, params = self.getPathParams()

        response: dict = {
            "message": "This is a GET request",
            "path": self.path,
            "path2": path,
            "params": params,
        }
        self.wfile.write(json.dumps(response).encode())

    def do_POST(self) -> None:

        path, params = self.getPathParams()
        
        post = self.getPost()

        response: dict = {
            "message": "This is a POST request",
            "received": post,
            "path": self.path,
            "path2": path,
            "params": params,
        }

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(json.dumps(response).encode())


def run(
        server_class = HTTPServer, #: Type[HTTPServer] = HTTPServer,
        handler_class = SimpleRequestHandler, #: Type[BaseHTTPRequestHandler] = SimpleRequestHandler,
        port: int = 8000
) -> None:
    server_address: tuple = ('', port)
    httpd: HTTPServer = server_class(server_address, handler_class)
    print(f"Starting HTTP server on port {port}...")
    httpd.serve_forever()

if __name__ == '__main__':
    run()