this repo has no description
at trunk 41 lines 1.5 kB view raw
1#!/usr/bin/env python3.10 2# Run from the root of the repository with 3# $ PYTHONPATH=. python3 examples/11_platforms/web/webplatform.py 4import http.server 5import os 6import socketserver 7 8from scrapscript import eval_exp, Apply, Record, parse, tokenize, String, Int 9 10HANDLER_FILE_NAME = "handler.scrap" 11PLATFORM_DIR_NAME = os.path.dirname(os.path.realpath(__file__)) 12with open(os.path.join(PLATFORM_DIR_NAME, HANDLER_FILE_NAME), "r") as f: 13 HANDLER = eval_exp({}, parse(tokenize(f.read()))) 14 15 16class WebPlatform(http.server.SimpleHTTPRequestHandler): 17 def handle_request(self) -> None: 18 result = eval_exp({}, Apply(HANDLER, String(self.path))) 19 assert isinstance(result, Record) 20 assert "code" in result.data 21 assert isinstance(result.data["code"], Int) 22 assert "body" in result.data 23 assert isinstance(result.data["body"], String) 24 self.send_response(result.data["code"].value) 25 # TODO(max): Move content-type into scrapscript code 26 # TODO(max): Serve scrap objects over the wire as 27 # application/scrapscript 28 self.send_header("Content-type", "text/html") 29 self.end_headers() 30 self.wfile.write(result.data["body"].value.encode("utf-8")) 31 32 def do_GET(self) -> None: 33 self.handle_request() 34 35 36server = socketserver.TCPServer 37server.allow_reuse_address = True 38with server(("", 8000), WebPlatform) as httpd: 39 host, port = httpd.server_address 40 print(f"serving at http://{host!s}:{port}") 41 httpd.serve_forever()