Created
November 11, 2025 03:41
-
-
Save benprew/7b11a985fc58553f18b3a30f9e865441 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| from http.server import BaseHTTPRequestHandler, HTTPServer | |
| from urllib.parse import urlparse, parse_qs | |
| DB = {} | |
| class KeyValueHandler(BaseHTTPRequestHandler): | |
| def send_404(self, message=b'ERROR: Unknown endpoint\n'): | |
| self.send_response(404) | |
| self.send_header('Content-type', 'text/plain') | |
| self.end_headers() | |
| self.wfile.write(message) | |
| def do_POST(self): | |
| parsed_path = urlparse(self.path) | |
| path = parsed_path.path | |
| query_params = parse_qs(parsed_path.query) | |
| if path != '/set': | |
| self.send_404() | |
| return | |
| for key, value_list in query_params.items(): | |
| DB[key] = value_list[0] | |
| self.send_response(200) | |
| self.send_header('Content-type', 'text/plain') | |
| self.end_headers() | |
| self.wfile.write(b'OK: Key-value pairs stored\n') | |
| def do_GET(self): | |
| parsed_path = urlparse(self.path) | |
| path = parsed_path.path | |
| query_params = parse_qs(parsed_path.query) | |
| if path != '/get': | |
| self.send_404() | |
| return | |
| key = query_params.get('key', [None])[0] | |
| if key is None: | |
| self.send_response(400) | |
| self.send_header('Content-type', 'text/plain') | |
| self.end_headers() | |
| self.wfile.write(b'ERROR: No key parameter provided\n') | |
| elif key in DB: | |
| self.send_response(200) | |
| self.send_header('Content-type', 'text/plain') | |
| self.end_headers() | |
| self.wfile.write(DB[key].encode('utf-8') + b'\n') | |
| else: | |
| self.send_404(b'ERROR: Key not found\n') | |
| def log_message(self, format, *args): | |
| print(f"[{self.log_date_time_string()}] {format % args}") | |
| def run_server(port=4000): | |
| server_address = ('', port) | |
| httpd = HTTPServer(server_address, KeyValueHandler) | |
| print(f'Server running on http://localhost:{port}/') | |
| print(f'Use POST /set?key=value to store data') | |
| print(f'Use GET /get?key=key to retrieve data') | |
| print('Press Ctrl+C to stop the server') | |
| try: | |
| httpd.serve_forever() | |
| except KeyboardInterrupt: | |
| print('\nServer stopped.') | |
| httpd.server_close() | |
| if __name__ == '__main__': | |
| run_server() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment