import json from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import urlparse, parse_qs class RequestHandler(BaseHTTPRequestHandler): def parse_path(self, request_path: str)-> dict: """ Parse request path """ parsed = urlparse(request_path) params_dict = parse_qs(parsed.query) return params_dict def store_urls(self, request_path: str)-> None: """ Parse URLs and store them """ params = self.parse_path(request_path) for key, val in params.items(): self.data_store.put_data(val[0]) def return_k_json(self, k:dict)-> BinaryIO: """ Return json response """ self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() # Contains the output stream for writing a response back to the client. # BufferedIOBase that writes to a stream # See https://docs.python.org/3/library/io.html#io.BufferedIOBase.write self.wfile.write(json.dumps(k).encode('utf-8')) def bad_request(self): """ Handle bad request """ self.send_response(400) self.send_header("Content-type", "application/json") self.end_headers() def do_GET(self): request_path = self.path if self.path == "/": self.return_k_json({"ciao": "mondo"}) if request_path.startswith("/get"): key = self.parse_path(request_path) self.return_k_json({"jars": key["key"]}) self.send_response(200) else: self.bad_request() self.end_headers() def do_POST(self): request_path = self.path if request_path.startswith("/set"): self.store_urls(request_path) self.send_response(200) else: self.bad_request() if __name__ == "__main__": host = "localhost" port = 8000 server = HTTPServer((host, port), RequestHandler) print("Server started http://%s:%s" % (host, port)) server.serve_forever()