import http.server import socketserver import cgi from urllib.parse import unquote, parse_qs import re import subprocess PORT = 8000 url_format = re.compile(r"^(?:(?:https://)?platform\.physik\.kit\.edu/codimd/)?(?P[\w_]+)([\?#].*)?$") class CodiToPdfHandler(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory="/app/html", **kwargs) # forward get requests def do_GET(self): print(self.path) print(self.headers) super().do_GET() return def do_POST(self): content_length = int(self.headers["Content-Length"]) _body = self.rfile.read(content_length) body = unquote(_body.decode("ASCII")) post_data = parse_qs(body) pad = post_data["pad"][0] pad_id = url_format.match(pad).group("id") subprocess.call(["codimd", "export", "--md", pad_id, "tmp.md"]) subprocess.call(["pandoc", "tmp.md", "-o", "tmp.pdf"]) pdf = open("tmp.pdf", "rb").read() subprocess.call(["rm", "tmp.md", "tmp.pdf"]) self.send_response(200) self.send_header("Content-Type", "application/pdf") self.send_header("Content-Length", str(len(pdf))) self.end_headers() self.wfile.write(pdf) return with http.server.ThreadingHTTPServer(("", PORT), CodiToPdfHandler) as httpd: httpd.serve_forever()