BlueGit

timfa posprint

Files

posprint / scripts / test-noconfirm / server.py

server.py

server.py 1.7 KiB Download Raw
1#!/usr/bin/env python3
2"""Minimal verify server for local noconfirm testing.
3
4GET /verify?code=84923 -> 200
5GET /verify?code=other -> 403
6GET anything else -> 404
7
8Run:
9 python scripts/test-noconfirm/server.py
10"""
11
12from __future__ import annotations
13
14from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15from urllib.parse import parse_qs, urlparse
16
17HOST = "127.0.0.1"
18PORT = 8765
19VALID_CODE = "84923"
20
21
22class Handler(BaseHTTPRequestHandler):
23 def log_message(self, fmt: str, *args) -> None:
24 print(f"[verify] {self.address_string()} {fmt % args}")
25
26 def do_GET(self) -> None:
27 parsed = urlparse(self.path)
28 if parsed.path.rstrip("/") != "/verify":
29 self._reply(404, "not found")
30 return
31 code = parse_qs(parsed.query).get("code", [None])[0]
32 if code == VALID_CODE:
33 self._reply(200, "ok")
34 else:
35 self._reply(403, "invalid code")
36
37 def _reply(self, status: int, body: str) -> None:
38 data = body.encode("utf-8")
39 self.send_response(status)
40 self.send_header("Content-Type", "text/plain; charset=utf-8")
41 self.send_header("Content-Length", str(len(data)))
42 self.end_headers()
43 self.wfile.write(data)
44
45
46def main() -> None:
47 server = ThreadingHTTPServer((HOST, PORT), Handler)
48 print(f"Listening on http://{HOST}:{PORT}")
49 print(f"Valid: http://{HOST}:{PORT}/verify?code={VALID_CODE} -> 200")
50 print(f"Invalid: http://{HOST}:{PORT}/verify?code=wrong -> 403")
51 print("Ctrl+C to stop")
52 server.serve_forever()
53
54
55if __name__ == "__main__":
56 main()