forked from sness/openmir
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiUtils.py
More file actions
94 lines (74 loc) · 3.12 KB
/
apiUtils.py
File metadata and controls
94 lines (74 loc) · 3.12 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
81
82
83
84
85
86
87
88
89
90
91
92
93
from tastypie.serializers import Serializer
import re
import json
class CORSResource(object):
"""
Adds CORS headers to resources that subclass this.
"""
def create_response(self, *args, **kwargs):
response = super(CORSResource, self).create_response(*args, **kwargs)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Content-Type'
return response
def method_check(self, request, allowed=None):
if allowed is None:
allowed = []
request_method = request.method.lower()
allows = ','.join(map(str.upper, allowed))
if request_method == 'options':
response = HttpResponse(allows)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Content-Type'
response['Allow'] = allows
raise ImmediateHttpResponse(response=response)
if not request_method in allowed:
response = http.HttpMethodNotAllowed(allows)
response['Allow'] = allows
raise ImmediateHttpResponse(response=response)
return request_method
class CamelCaseJSONSerializer(Serializer):
formats = ['json','jsonp']
content_types = {
'json': 'application/json',
'jsonp': 'application/jsonp',
}
def to_json(self, data, options=None):
# Changes underscore_separated names to camelCase names to go
# from python convention to javacsript convention
data = self.to_simple(data, options)
def underscoreToCamel(match):
return match.group()[0] + match.group()[2].upper()
def camelize(data):
if isinstance(data, dict):
new_dict = {}
for key, value in data.items():
new_key = re.sub(r"[a-z]_[a-z]", underscoreToCamel, key)
new_dict[new_key] = camelize(value)
return new_dict
if isinstance(data, (list, tuple)):
for i in range(len(data)):
data[i] = camelize(data[i])
return data
return data
camelized_data = camelize(data)
return json.dumps(camelized_data, sort_keys=True)
def from_json(self, content):
# Changes camelCase names to underscore_separated names to go
# from javascript convention to python convention
data = json.loads(content)
def camelToUnderscore(match):
return match.group()[0] + "_" + match.group()[1].lower()
def underscorize(data):
if isinstance(data, dict):
new_dict = {}
for key, value in data.items():
new_key = re.sub(r"[a-z][A-Z]", camelToUnderscore, key)
new_dict[new_key] = underscorize(value)
return new_dict
if isinstance(data, (list, tuple)):
for i in range(len(data)):
data[i] = underscorize(data[i])
return data
return data
underscored_data = underscorize(data)
return underscored_data