-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
80 lines (70 loc) · 3.07 KB
/
Copy pathserver.py
File metadata and controls
80 lines (70 loc) · 3.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import json
from typing import Union
from svg import SVGElement
import tornado.ioloop
import tornado.web
from urllib import parse
import logging
from cairosvg import svg2png
from artist import visualizeBinaryTree
from tree import ListBasedBinaryTree
class ElementsHandler(tornado.web.RequestHandler):
def requestToSVG(self) -> Union[SVGElement, None]:
if len(self.request.body) > 500:
self.set_status(400, "request too long")
self.finish()
logging.debug("denied request for being "+str(len(self.request.body))+" bytes long")
return None
try:
treeData = json.loads(self.request.body)
except:
self.set_status(400, "invalid JSON")
self.finish()
logging.debug("denied request for being invalid JSON")
return None
if "elements" not in treeData or type(
treeData["elements"]) is not list or "squares" not in treeData or type(
treeData["squares"]) is not bool or "bg" not in treeData or type(
treeData["bg"]) is not bool:
self.set_status(400, "malformed request")
self.finish()
logging.debug("denied request for having malformed input: "+str(treeData))
return None
elements = [(x.strip()[:10] if x.strip() != "" else None)
for x in treeData["elements"]]
svgResult = visualizeBinaryTree(
ListBasedBinaryTree(elements),
treeData["squares"],
treeData["squaresBlack"],
treeData["bg"])
logging.info("processed request for tree: "+str(treeData))
return svgResult
class SVGHandler(ElementsHandler):
def post(self):
svg = super().requestToSVG()
if svg is not None:
dataURL = "data:image/svg+xml," + parse.quote(svg.render())
self.set_header("Content-Type", "application/json")
self.finish({"width": svg.viewBoxWidth, "url": dataURL})
class PNGHandler(ElementsHandler):
def post(self):
svg = super().requestToSVG()
if svg is not None:
png = svg2png(bytestring=svg.render(), output_width=svg.viewBoxWidth*2)
self.set_header("Content-Type", "image/png")
self.finish(png)
if __name__ == "__main__":
application = tornado.web.Application([(r"/svg", SVGHandler),
(r"/png", PNGHandler),
(r"/(.*)",
tornado.web.StaticFileHandler, {
"path": "./static/",
"default_filename": "index.html"
})],
compress_response=True)
application.listen(8888)
print("listening on port 8888")
logging.basicConfig(
filename='requests.log', encoding='utf-8', level=logging.DEBUG,
format='%(asctime)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
tornado.ioloop.IOLoop.current().start()