"""Local test server for Quill.
python server.py -> http://127.0.0.1:8792
"""
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
from api import render_query
from quill import INKS, STYLES
PORT = int(os.environ.get("PORT") or (sys.argv[1] if len(sys.argv) > 1 else 8792))
HOST = "0.0.0.0" if "PORT" in os.environ else "127.0.0.1" # Heroku sets PORT
PAGE = """
Quill
Quill
Calligraphy with hand-set pens over public stroke data (Hershey letters, KanjiVG kanji and kana). No training. Kanji or kana switch to the shodo brush automatically.
"""
def page():
opts = lambda xs: "".join(f'' for x in xs)
return (PAGE.replace("__STYLES__", opts(STYLES)).replace("__INKS__", opts(INKS))
.replace("__ALL__", json.dumps(list(STYLES))))
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1" # HTTP/1.0 closes right after writing; on this Windows box that RSTs larger bodies
def send(self, body, ctype, code=200):
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self):
url = urlparse(self.path)
if url.path == "/":
self.send(page().encode(), "text/html; charset=utf-8")
elif url.path == "/render":
code, body = render_query(url.query)
self.send(json.dumps(body).encode(), "application/json", code)
else:
self.send(b"not found", "text/plain", 404)
def log_message(self, *a):
pass
if __name__ == "__main__":
print(f"Quill on http://{HOST}:{PORT}", flush=True)
ThreadingHTTPServer((HOST, PORT), Handler).serve_forever()