Skip to content

Instantly share code, notes, and snippets.

@convexset
Last active February 13, 2023 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save convexset/07a5feac651563ced644b3d069bc0b9a to your computer and use it in GitHub Desktop.
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)
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