-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpretty_json.py
91 lines (73 loc) · 3.29 KB
/
pretty_json.py
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
81
82
83
84
85
86
87
88
89
90
91
import logging
from tornado.options import options
import tornado.web
import tornado.template
import json
import os
class PrettyJsonRequestHandler(tornado.web.RequestHandler):
def prepare(self):
path_to_file = os.path.abspath(__file__)
path_to_project = path_to_file[:path_to_file.rfind("Addama")]
template_path = "/%s/Addama/templates" % path_to_project.strip("/")
self.template_loader = tornado.template.Loader(template_path)
def write(self, arg):
self.annotate_service_root(arg)
if isinstance(arg, (list)):
if self.show_api(): return
return super(PrettyJsonRequestHandler, self).write(json.dumps(arg))
elif type(arg) is dict:
if self.show_api(): return
return super(PrettyJsonRequestHandler, self).write(json.dumps(arg, indent=4))
elif isinstance(arg, basestring):
try:
j = json.loads(arg)
if self.show_api(): return
return super(PrettyJsonRequestHandler, self).write(json.dumps(j, indent=4))
except:
if options.verbose: logging.warning("unable to convert to json")
return super(PrettyJsonRequestHandler, self).write(arg)
def write_error(self, status_code, **kwargs):
error_msg = kwargs["exc_info"][1]
if options.verbose: logging.info("write_error(%s):%s" % (status_code, error_msg))
h_accept = self.request.headers["Accept"]
if options.verbose: logging.info("h_accept=%s" % str(h_accept))
if "text/html" in h_accept.split(","):
html = self.template_loader.load("errors.html").generate(status_code=status_code, error_message=error_msg)
super(PrettyJsonRequestHandler, self).write(html)
else:
self.write({ "message": str(error_msg) })
def show_api(self):
h_accept = self.request.headers["Accept"]
if options.verbose: logging.info("h_accept=%s" % str(h_accept))
if "text/html" in h_accept.split(","):
path_url = self.request.uri
root_url = ""
if options.service_root != "/":
root_url = "/" + options.service_root.strip("/")
path_url = root_url + self.request.uri
html = self.template_loader.load("apis.html").generate(url=path_url, root_path=root_url)
super(PrettyJsonRequestHandler, self).write(html)
return True
return False
def annotate_service_root(self, arg):
if isinstance(arg, (list)):
for item in arg:
self.annotate_service_root(item)
elif type(arg) is dict:
if "uri" in arg:
if options.service_root != "/":
arg["uri"] = "/" + options.service_root.strip("/") + arg["uri"]
for key in ["items", "files", "directories"]:
if key in arg:
for item in arg[key]:
self.annotate_service_root(item)
def jsonable(self, item):
json_item = {}
for k in item.iterkeys():
if k == "_id":
json_item["_id"] = str(item["_id"])
elif "[]" in k:
json_item[k.replace("[]", "")] = item[k]
elif k != "owner":
json_item[k] = item[k]
return json_item