forked from OCA/rest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restapi.py
433 lines (368 loc) · 17.3 KB
/
restapi.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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# Copyright 2018 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import abc
import functools
import json
from cerberus import Validator
from odoo import _, http
from odoo.exceptions import UserError, ValidationError
from .tools import ROUTING_DECORATOR_ATTR, 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
setattr(response_wrap, ROUTING_DECORATOR_ATTR, routing)
response_wrap.original_func = f
return response_wrap
return decorator
class RestMethodParam(abc.ABC):
@abc.abstractmethod
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
"""
@abc.abstractmethod
def to_response(self, service, result) -> http.Response:
"""
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
"""
@abc.abstractmethod
def to_openapi_query_parameters(self, service, spec) -> dict:
return {}
@abc.abstractmethod
def to_openapi_requestbody(self, service, spec) -> dict:
return {}
@abc.abstractmethod
def to_openapi_responses(self, service, spec) -> dict:
return {}
@abc.abstractmethod
def to_json_schema(self, service, spec, direction) -> dict:
return {}
class BinaryData(RestMethodParam):
def __init__(self, mediatypes="*/*", required=False):
if not isinstance(mediatypes, list):
mediatypes = [mediatypes]
self._mediatypes = mediatypes
self._required = required
def to_json_schema(self, service, spec, direction):
return {
"type": "string",
"format": "binary",
"required": self._required,
}
@property
def _binary_content_schema(self):
return {
mediatype: {"schema": self.to_json_schema(None, None, None)}
for mediatype in self._mediatypes
}
def to_openapi_requestbody(self, service, spec):
return {"content": self._binary_content_schema}
def to_openapi_query_parameters(self, service, spec):
raise NotImplementedError(
"BinaryData are not (?yet?) supported as query paramters"
)
def to_openapi_responses(self, service, spec):
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, spec):
json_schema = self.to_json_schema(service, spec, "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, spec):
json_schema = self.to_json_schema(service, spec, "input")
return {"content": {"application/json": {"schema": json_schema}}}
def to_openapi_responses(self, service, spec):
json_schema = self.to_json_schema(service, spec, "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, spec, 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, spec):
raise NotImplementedError("List are not (?yet?) supported as query paramters")
# pylint: disable=W8120,W8115
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 %(idx)s :%(errors)s",
idx=idx,
errors=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 (%(current)s < %(expected)s)",
current=len(values),
expected=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 (%(current)s > %(expected)s)",
current=len(values),
expected=self._max_items,
)
)
return values
def to_json_schema(self, service, spec, 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
class MultipartFormData(RestMethodParam):
def __init__(self, parts):
"""This allows to create multipart/form-data endpoints.
:param parts: list of RestMethodParam
"""
if not isinstance(parts, dict):
raise ValidationError(_("You must provide a dict of RestMethodParam"))
self._parts = parts
def to_openapi_properties(self, service, spec, direction):
properties = {}
for key, part in self._parts.items():
properties[key] = part.to_json_schema(service, spec, direction)
return properties
def to_openapi_encoding(self):
encodings = {}
for key, part in self._parts.items():
if isinstance(part, BinaryData):
encodings[key] = {"contentType": ", ".join(part._mediatypes)}
return encodings
def to_json_schema(self, service, spec, direction):
res = {
"multipart/form-data": {
"schema": {
"type": "object",
"properties": self.to_openapi_properties(service, spec, direction),
}
}
}
encoding = self.to_openapi_encoding()
if len(encoding) > 0:
res["multipart/form-data"]["schema"]["encoding"] = encoding
return res
def from_params(self, service, params):
for key, part in self._parts.items():
param = None
if isinstance(part, BinaryData):
param = part.from_params(service, params[key])
else:
# If the part is not Binary, it should be JSON
try:
json_param = json.loads(
params[key]
) # multipart ony sends its parts as string
except json.JSONDecodeError as error:
raise ValidationError(
_(
"%(key)'s JSON content is malformed: %(error)s",
key=key,
error=error,
)
) from error
param = part.from_params(service, json_param)
params[key] = param
return params
def to_openapi_query_parameters(self, service, spec):
raise NotImplementedError(
"MultipartFormData are not (?yet?) supported as query paramters"
)
def to_openapi_requestbody(self, service, spec):
return {"content": self.to_json_schema(service, spec, "input")}
def to_openapi_responses(self, service, spec):
return {"200": {"content": self.to_json_schema(service, spec, "output")}}
def to_response(self, service, result):
raise NotImplementedError()