|
| 1 | +###### WORDS OF WARNING |
| 2 | +# This implements a simple http JSON "RPC" server for the generator |
| 3 | +# |
| 4 | +# The keyword here is simple! You do NOT want to run this open on the |
| 5 | +# internet. It is purely a way to get a UI for developers of the generator |
| 6 | +# up and running, easily without having to spin up docker or anything else. |
| 7 | +# |
| 8 | +# More specifically this is not intented to be the RPC server that we will |
| 9 | +# offer to the outside world. This is just a quick-dirty test bed for RPCs |
| 10 | +# + the thing needed to provide the UI. |
| 11 | +import sys |
| 12 | +import json |
| 13 | +from generatorcore.inputs import Inputs |
| 14 | +from generatorcore.generator import calculate |
| 15 | +from generatorcore.refdata import RefData |
| 16 | +from generatorcore.makeentries import make_entries |
| 17 | +from http.server import HTTPServer, BaseHTTPRequestHandler |
| 18 | + |
| 19 | + |
| 20 | +def cmd_explorer(args): |
| 21 | + rd = RefData.load() |
| 22 | + with open("explorer/index.html") as index_file: |
| 23 | + index = index_file.read() |
| 24 | + |
| 25 | + class ExplorerHandler(BaseHTTPRequestHandler): |
| 26 | + def handle_index(self): |
| 27 | + self.send_response(200) |
| 28 | + self.send_header("Content-type", "text/html") |
| 29 | + self.end_headers() |
| 30 | + self.wfile.write(index.encode()) |
| 31 | + |
| 32 | + def handle_calculate(self, ags, year): |
| 33 | + error = None |
| 34 | + response = "" |
| 35 | + try: |
| 36 | + e = make_entries(rd, ags, year) |
| 37 | + inputs = Inputs( |
| 38 | + facts_and_assumptions=rd.facts_and_assumptions(), entries=e |
| 39 | + ) |
| 40 | + g = calculate(inputs) |
| 41 | + response = json.dumps(g.result_dict()) |
| 42 | + except Exception as e: |
| 43 | + error = e |
| 44 | + |
| 45 | + if error is None: |
| 46 | + self.send_response(200) |
| 47 | + self.send_header("Content-type", "application/json") |
| 48 | + self.end_headers() |
| 49 | + self.wfile.write(response.encode()) |
| 50 | + else: |
| 51 | + self.send_response(500) |
| 52 | + print(error) |
| 53 | + |
| 54 | + def do_GET(self): |
| 55 | + print(self.command) |
| 56 | + print(self.path.split("/")) |
| 57 | + match self.path.split("/"): |
| 58 | + case ["", "calculate", ags, year]: |
| 59 | + self.handle_calculate(ags, int(year)) |
| 60 | + |
| 61 | + case ["", ""]: |
| 62 | + self.handle_index() |
| 63 | + |
| 64 | + case other: |
| 65 | + self.send_response(404) |
| 66 | + self.end_headers() |
| 67 | + return |
| 68 | + |
| 69 | + httpd = HTTPServer(("", 4070), ExplorerHandler) |
| 70 | + httpd.serve_forever() |
0 commit comments