Last active
February 13, 2023 12:38
-
-
Save convexset/07a5feac651563ced644b3d069bc0b9a to your computer and use it in GitHub Desktop.
Python HTTP Server Example for Controlling the Number of "Serves" (This allows infinite GETs, and stops after the first POST)
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
import http.server | |
from pprint import pprint | |
done = False | |
def do_echo(self): | |
print(f'Headers:') | |
pprint(dict(self.headers.items())) | |
print() | |
print(f'From: {self.client_address[0]}:{self.client_address[1]}') | |
print() | |
print(f'Operation: {self.command} {self.path}') | |
print() | |
content_length = int(self.headers.get('Content-Length', 0)) | |
body = self.rfile.read(content_length) | |
print(f'Body (length={content_length}):') | |
print(body.decode('utf-8')) | |
print() | |
self.send_response(200, 'OK') | |
self.end_headers() | |
self.wfile.write(f'{self.command} {self.path}\n'.encode('utf-8')) | |
self.wfile.write(body) | |
class Handler(http.server.BaseHTTPRequestHandler): | |
def do_GET(self): | |
global done | |
do_echo(self) | |
def do_POST(self): | |
global done | |
do_echo(self) | |
done = True | |
with http.server.HTTPServer(('', 3000), Handler) as httpd: | |
while not done: | |
httpd.handle_request() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment