forked from ajepe/odoo-addons
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.py
164 lines (142 loc) · 4.65 KB
/
common.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""Common methods"""
import ast
import logging
import json
from odoo.http import Response
from odoo.tools import date_utils
_logger = logging.getLogger(__name__)
def token_response(data):
"""Token Response
This will be return when token request was successfully processed."""
return Response(
json.dumps(data),
status=200,
content_type='application/json; charset=utf-8',
headers=[
('Cache-Control', 'no-store'),
('Pragma', 'no-cache')
]
)
def valid_response(data, status=200):
"""Valid Response
This will be return when the http request was successfully processed."""
response = None
if data is None:
response = None
elif isinstance(data, str):
response = json.dumps({
'message': data
})
elif isinstance(data, list):
response = json.dumps({
'count': len(data),
'data': data
}, sort_keys=True, default=date_utils.json_default)
else:
response = json.dumps({
'data': data
}, sort_keys=True, default=date_utils.json_default)
return Response(
response,
status=status,
content_type='application/json; charset=utf-8'
)
def invalid_response(error, message=None, status=401):
"""Invalid Response
This will be the return value whenever the server runs into an error
either from the client or the server."""
response = json.dumps({
'type': error,
'message': str(message) if str(message) else 'wrong arguments (missing validation)'
})
return Response(
response,
status=status,
content_type='application/json; charset=utf-8'
)
def prepare_response(data, one=False):
"""Replaces ids as lists with two different keys with id and string values.
Like: {country_id: [1, 'United States'], company_currency: [1, 'EUR']} => {country_id: 1, country: 'United States', company_currency_id: 1, company_currency: 'EUR'}.
Also records in Odoo are lists, and when we need only record itself, returned first list item or None"""
result = None
if isinstance(data, list):
result = []
for _result in data:
if isinstance(_result, dict):
item = {}
for key, value in _result.items():
if isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], int) and isinstance(value[1], str):
_int, _str = value
_key = key.replace('_id', '').replace('_uid', '')
_key_id = '{}_id'.format(_key)
item[_key_id] = _int
item[_key] = _str
else:
item[key] = value
else:
item = _result
result.append(item)
if one:
if len(result) > 0:
result = result[0]
else:
result = None
return result
def parse_dict(obj):
keys = list(obj.keys())
if len(keys) == 0:
return None
key = keys[0]
if len(key) == 0:
return None
value = obj[key]
left, center, right = '', '', value
if key[-1] == '!':
center = '!='
left = key[0:-1]
else:
center = '='
left = key
return (left, center, right)
def parse_expr(expr):
if isinstance(expr, tuple):
return expr
if isinstance(expr, list):
return tuple(expr)
elif isinstance(expr, dict):
return parse_dict(expr)
def parse_domain(prepared):
result = []
for expr in prepared:
obj = parse_expr(expr)
if obj:
result.append(obj)
return result
def parse_list(domain):
if isinstance(domain, str):
if not (domain[0] == '[' and domain[-1] == ']'):
domain = '[{0}]'.format(domain)
domain = ast.literal_eval(domain)
return domain
def extract_arguments(payload={}):
"""Parse "[('id','=','100')]" or {'id': '100'} notation as domain
"""
domain, fields, offset, limit, order = [], [], 0, 0, None
_domain = payload.get('domain')
_fields = payload.get('fields')
_offset = payload.get('offset')
_limit = payload.get('limit')
_order = payload.get('order')
if _domain:
domain_list = parse_list(_domain)
domain = parse_domain(domain_list)
if _fields:
fields += parse_list(_fields)
if _offset:
offset = int(_offset)
if _limit:
limit = int(_limit)
if _order:
parsed_order = parse_list(_order)
order = ','.join(parsed_order) if parsed_order else None
return [domain, fields, offset, limit, order]