forked from CLIxIndia-Dev/unplatform_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
87 lines (73 loc) · 2.9 KB
/
utilities.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
import functools
import json
import web
CORS_HEADERS = "Content-Type,Authorization,X-Api-Proxy,X-Api-Key,request-line,X-Api-Locale"
class BaseClass:
def __init__(self):
pass
def OPTIONS(self, *args, **kwargs):
# https://www.youtube.com/watch?v=gZelOtYjYv8
web.header("Access-Control-Allow-Origin", "*")
web.header("Access-Control-Allow-Credentials", "true")
web.header("Access-Control-Allow-Headers", CORS_HEADERS)
web.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
web.header("Access-Control-Max-Age", "1728000")
return
@staticmethod
def data():
try:
return json.loads(web.data())
except (ValueError, TypeError):
return {}
def format_html_response(func):
"""set html header"""
@functools.wraps(func)
def wrapper(self, *args):
results = func(self, *args)
web.header('Content-type', 'text/html')
return results
return wrapper
def format_response(func):
"""set json header and convert response to json string"""
@functools.wraps(func)
def wrapper(self, *args):
results = func(self, *args)
web.header('Content-type', 'application/json')
web.header("Access-Control-Allow-Origin", "*")
web.header("Access-Control-Allow-Credentials", "true")
web.header("Access-Control-Allow-Headers", CORS_HEADERS)
web.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
web.header("Access-Control-Max-Age", "1728000")
if isinstance(results, dict) or isinstance(results, list):
return json.dumps(results)
else:
return results
return wrapper
def format_xml_response(func):
"""set json header and convert response to json string"""
@functools.wraps(func)
def wrapper(self, *args):
results = func(self, *args)
web.header('Content-type', 'application/xml')
web.header("Access-Control-Allow-Origin", "*")
web.header("Access-Control-Allow-Credentials", "true")
web.header("Access-Control-Allow-Headers", CORS_HEADERS)
web.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
web.header("Access-Control-Max-Age", "1728000")
if isinstance(results, dict):
return json.dumps(results)
else:
return results
return wrapper
def allow_cors(func):
"""set cors headers"""
@functools.wraps(func)
def wrapper(self, *args):
results = func(self, *args)
web.header("Access-Control-Allow-Origin", "*")
web.header("Access-Control-Allow-Credentials", "true")
web.header("Access-Control-Allow-Headers", CORS_HEADERS)
web.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
web.header("Access-Control-Max-Age", "1728000")
return results
return wrapper