forked from OCA/rest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestapi.py
More file actions
335 lines (283 loc) · 13.7 KB
/
restapi.py
File metadata and controls
335 lines (283 loc) · 13.7 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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# Copyright 2018 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import functools
from cerberus import Validator
from odoo import _, http
from odoo.exceptions import UserError
from .tools import cerberus_to_json
def method(routes, input_param=None, output_param=None, **kw):
"""Decorator marking the decorated method as being a handler for
REST requests. The method must be part of a component inheriting from
``base.rest.service``.
:param routes: list of tuple (path, http method). path is a string or
array.
Each tuple determines which http requests and http method
will match the decorated method. The path part can be a
single string or an array of strings. See werkzeug's routing
documentation for the format of path expression (
http://werkzeug.pocoo.org/docs/routing/ ).
:param: input_param: An instance of an object that implemented
``RestMethodParam``. When processing a request, the http
handler first call the from_request method and then call the
decorated method with the result of this call.
:param: output_param: An instance of an object that implemented
``RestMethodParam``. When processing the result of the
call to the decorated method, the http handler first call
the `to_response` method with this result and then return
the result of this call.
:param auth: The type of authentication method. A special auth method
named 'public_or_default' can be used. In such a case
when the HTTP route will be generated, the auth method
will be computed from the '_default_auth' property defined
on the controller with 'public_or_' as prefix.
The purpose of 'public_or_default' auth method is to provide
a way to specify that a method should work for anonymous users
but can be enhanced when an authenticated user is know.
It implies that when the 'default' auth part of 'public_or_default'
will be replaced by the default_auth specified on the controller
in charge of registering the web services, an auth method with
the same name is defined into odoo to provide such a behavior.
In the following example, the auth method on my ping service
will be `public_or_jwt` since this authentication method is
provided by the auth_jwt addon.
.. code-block:: python
class PingService(Component):
_inherit = "base.rest.service"
_name = "ping_service"
_usage = "ping"
_collection = "test.api.services"
@restapi.method(
[(["/<string:message>""], "GET")],
auth="public_or_auth",
)
def _ping(self, message):
return {"message": message}
class MyRestController(main.RestController):
_root_path = '/test/'
_collection_name = "test.api.services"
_default_auth = "jwt'
:param cors: The Access-Control-Allow-Origin cors directive value. When
set, this automatically adds OPTIONS to allowed http methods
so the Odoo request handler will accept it.
:param bool csrf: Whether CSRF protection should be enabled for the route.
Defaults to ``False``
:param bool save_session: Whether HTTP session should be saved into the
session store: Default to ``True``
"""
def decorator(f):
_routes = []
for paths, http_methods in routes:
if not isinstance(paths, list):
paths = [paths]
if not isinstance(http_methods, list):
http_methods = [http_methods]
if kw.get("cors") and "OPTIONS" not in http_methods:
http_methods.append("OPTIONS")
for m in http_methods:
_routes.append(([p for p in paths], m))
routing = {
"routes": _routes,
"input_param": input_param,
"output_param": output_param,
}
routing.update(kw)
@functools.wraps(f)
def response_wrap(*args, **kw):
response = f(*args, **kw)
return response
response_wrap.routing = routing
response_wrap.original_func = f
return response_wrap
return decorator
class RestMethodParam(object):
def from_params(self, service, params):
"""
This method is called to process the parameters received at the
controller. This method should validate and sanitize these paramaters.
It could also be used to transform these parameters into the format
expected by the called method
:param service:
:param request: `HttpRequest.params`
:return: Value into the format expected by the method
"""
def to_response(self, service, result):
"""
This method is called to prepare the result of the call to the method
in a format suitable by the controller (http.Response or JSON dict).
It's responsible for validating and sanitizing the result.
:param service:
:param obj:
:return: http.Response or JSON dict
"""
def to_openapi_query_parameters(self, service):
return {}
def to_openapi_requestbody(self, service):
return {}
def to_openapi_responses(self, service):
return {}
class BinaryData(RestMethodParam):
def __init__(self, mediatypes="*/*", required=False):
if not isinstance(mediatypes, list):
mediatypes = [mediatypes]
self._mediatypes = mediatypes
self._required = required
@property
def _binary_content_schema(self):
return {
mediatype: {
"schema": {
"type": "string",
"format": "binary",
"required": self._required,
}
}
for mediatype in self._mediatypes
}
def to_openapi_requestbody(self, service):
return {"content": self._binary_content_schema}
def to_openapi_responses(self, service):
return {"200": {"content": self._binary_content_schema}}
def to_response(self, service, result):
if not isinstance(result, http.Response):
# The response has not been build by the called method...
result = self._to_http_response(result)
return result
def from_params(self, service, params):
return params
def _to_http_response(self, result):
mediatype = self._mediatypes[0] if len(self._mediatypes) == 1 else "*/*"
headers = [
("Content-Type", mediatype),
("X-Content-Type-Options", "nosniff"),
("Content-Disposition", http.content_disposition("file")),
("Content-Length", len(result)),
]
return http.request.make_response(result, headers)
class CerberusValidator(RestMethodParam):
def __init__(self, schema):
"""
:param schema: can be dict as cerberus schema, an instance of
cerberus.Validator or a sting with the method name to
call on the service to get the schema or the validator
"""
self._schema = schema
def from_params(self, service, params):
validator = self.get_cerberus_validator(service, "input")
if validator.validate(params):
return validator.document
raise UserError(_("BadRequest %s") % validator.errors)
def to_response(self, service, result):
validator = self.get_cerberus_validator(service, "output")
if validator.validate(result):
return validator.document
raise SystemError(_("Invalid Response %s") % validator.errors)
def to_openapi_query_parameters(self, service):
json_schema = self.to_json_schema(service, "input")
parameters = []
for prop, spec in list(json_schema["properties"].items()):
params = {
"name": prop,
"in": "query",
"required": prop in json_schema["required"],
"allowEmptyValue": spec.get("nullable", False),
"default": spec.get("default"),
}
if spec.get("schema"):
params["schema"] = spec.get("schema")
else:
params["schema"] = {"type": spec["type"]}
if spec.get("items"):
params["schema"]["items"] = spec.get("items")
if "enum" in spec:
params["schema"]["enum"] = spec["enum"]
parameters.append(params)
if spec["type"] == "array":
# To correctly handle array into the url query string,
# the name must ends with []
params["name"] = params["name"] + "[]"
return parameters
def to_openapi_requestbody(self, service):
json_schema = self.to_json_schema(service, "input")
return {"content": {"application/json": {"schema": json_schema}}}
def to_openapi_responses(self, service):
json_schema = self.to_json_schema(service, "output")
return {"200": {"content": {"application/json": {"schema": json_schema}}}}
def get_cerberus_validator(self, service, direction):
assert direction in ("input", "output")
schema = self._schema
if isinstance(self._schema, str):
validator_component = service.component(usage="cerberus.validator")
schema = validator_component.get_validator_handler(
service, self._schema, direction
)()
if isinstance(schema, Validator):
return schema
if isinstance(schema, dict):
return Validator(schema, purge_unknown=True)
raise Exception(_("Unable to get cerberus schema from %s") % self._schema)
def to_json_schema(self, service, direction):
schema = self.get_cerberus_validator(service, direction).schema
return cerberus_to_json(schema)
class CerberusListValidator(CerberusValidator):
def __init__(self, schema, min_items=None, max_items=None, unique_items=None):
"""
:param schema: Cerberus list item schema
can be dict as cerberus schema, an instance of
cerberus.Validator or a sting with the method name to
call on the service to get the schema or the validator
:param min_items: A list instance is valid against "min_items" if its
size is greater than, or equal to, min_items.
The value MUST be a non-negative integer.
:param max_items: A list instance is valid against "max_items" if its
size is less than, or equal to, max_items.
The value MUST be a non-negative integer.
:param unique_items: Used to document that the list should only
contain unique items.
(Not enforced at validation time)
"""
super(CerberusListValidator, self).__init__(schema=schema)
self._min_items = min_items
self._max_items = max_items
self._unique_items = unique_items
def from_params(self, service, params):
return self._do_validate(service, data=params, direction="input")
def to_response(self, service, result):
return self._do_validate(service, data=result, direction="output")
def to_openapi_query_parameters(self, service):
raise NotImplementedError("List are not (?yet?) supported as query paramters")
def _do_validate(self, service, data, direction):
validator = self.get_cerberus_validator(service, direction)
values = []
ExceptionClass = UserError if direction == "input" else SystemError
for idx, p in enumerate(data):
if not validator.validate(p):
raise ExceptionClass(
_("BadRequest item %s :%s") % (idx, validator.errors)
)
values.append(validator.document)
if self._min_items is not None and len(values) < self._min_items:
raise ExceptionClass(
_(
"BadRequest: Not enough items in the list (%s < %s)"
% (len(values), self._min_items)
)
)
if self._max_items is not None and len(values) > self._max_items:
raise ExceptionClass(
_(
"BadRequest: Too many items in the list (%s > %s)"
% (len(values), self._max_items)
)
)
return values
def to_json_schema(self, service, direction):
cerberus_schema = self.get_cerberus_validator(service, direction).schema
json_schema = cerberus_to_json(cerberus_schema)
json_schema = {"type": "array", "items": json_schema}
if self._min_items is not None:
json_schema["minItems"] = self._min_items
if self._max_items is not None:
json_schema["maxItems"] = self._max_items
if self._unique_items is not None:
json_schema["uniqueItems"] = self._unique_items
return json_schema