"""Local HTTP demonstration. No external requests, credentials or MIYAIP service calls.""" from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlsplit import json import time class DemoHandler(BaseHTTPRequestHandler): def log_message(self, *_): pass def reply(self, code, body=b"", headers=None): self.send_response(code) for key, value in (headers or {}).items(): self.send_header(key, value) self.send_header("Content-Length", str(len(body))) try: self.end_headers() self.wfile.write(body) except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError): pass def do_CONNECT(self): self.reply(407, headers={"Proxy-Authenticate": 'Basic realm="local-demo"'}) def do_GET(self): path = urlsplit(self.path).path if path == "/redirect": return self.reply(302, headers={"Location": "/headers"}) if path == "/loop": return self.reply(302, headers={"Location": "/loop"}) if path == "/slow": time.sleep(2) if path in {"/headers", "/slow"}: payload = {"method": self.command, "headers": dict(self.headers)} return self.reply(200, json.dumps(payload, indent=2).encode(), {"Content-Type": "application/json"}) self.reply(404, b"Use /headers, /redirect, /loop or /slow") def do_POST(self): body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) if urlsplit(self.path).path == "/redirect307": return self.reply(307, headers={"Location": "/headers"}) if urlsplit(self.path).path == "/redirect302": return self.reply(302, headers={"Location": "/headers"}) payload = {"method": self.command, "headers": dict(self.headers), "body": body.decode("utf-8", errors="replace")} self.reply(200, json.dumps(payload, indent=2).encode(), {"Content-Type": "application/json"}) if __name__ == "__main__": print("Local demonstration: http://127.0.0.1:8766 (Ctrl+C to stop)", flush=True) ThreadingHTTPServer(("127.0.0.1", 8766), DemoHandler).serve_forever()