forked from OCA/rest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restapi.py
218 lines (191 loc) · 7.83 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
# Copyright 2021 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import _
from odoo.exceptions import UserError
from odoo.addons.base_rest import restapi
from pydantic import BaseModel, ValidationError, validate_model
def replace_ref_in_schema(item, original_schema):
if isinstance(item, list):
return [replace_ref_in_schema(i, original_schema) for i in item]
elif isinstance(item, dict):
if list(item.keys()) == ["$ref"]:
schema = item["$ref"].split("/")[-1]
return {"$ref": f"#/components/schemas/{schema}"}
else:
return {
key: replace_ref_in_schema(i, original_schema)
for key, i in item.items()
}
else:
return item
class PydanticModel(restapi.RestMethodParam):
def __init__(self, cls: BaseModel):
"""
:param name: The pydantic model name
"""
if not issubclass(cls, BaseModel):
raise TypeError(
f"{cls} is not a subclass of odoo.addons.pydantic.models.BaseModel"
)
self._model_cls = cls
def from_params(self, service, params):
try:
return self._model_cls(**params)
except ValidationError as ve:
raise UserError(_("BadRequest %s") % ve.json(indent=0))
def to_response(self, service, result):
# do we really need to validate the instance????
json_dict = result.dict()
to_validate = (
json_dict if not result.__config__.orm_mode else result.dict(by_alias=True)
)
*_, validation_error = validate_model(self._model_cls, to_validate)
if validation_error:
raise SystemError(_("Invalid Response %s") % validation_error)
return json_dict
def to_openapi_query_parameters(self, servic, spec):
json_schema = self._model_cls.schema()
parameters = []
for prop, spec in list(json_schema["properties"].items()):
params = {
"name": prop,
"in": "query",
"required": prop in json_schema.get("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
# TODO, we should probably get the spec as parameters. That should
# allows to add the definition of a schema only once into the specs
# and use a reference to the schema into the parameters
def to_openapi_requestbody(self, service, spec):
return {
"content": {
"application/json": {
"schema": self.to_json_schema(service, spec, "input")
}
}
}
def to_openapi_responses(self, service, spec):
return {
"200": {
"content": {
"application/json": {
"schema": self.to_json_schema(service, spec, "output")
}
}
}
}
def to_json_schema(self, service, spec, direction):
schema = self._model_cls.schema(by_alias=False)
schema_name = schema["title"]
if schema_name not in spec.components.schemas:
definitions = schema.get("definitions", {})
for name, sch in definitions.items():
if name in spec.components.schemas:
continue
sch = replace_ref_in_schema(sch, sch)
spec.components.schema(name, sch)
schema = replace_ref_in_schema(schema, schema)
spec.components.schema(schema_name, schema)
return {"$ref": f"#/components/schemas/{schema_name}"}
class PydanticModelList(PydanticModel):
def __init__(
self,
cls: BaseModel,
min_items: int = None,
max_items: int = None,
unique_items: bool = None,
):
"""
:param name: The pydantic model name
: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().__init__(cls=cls)
self._min_items = min_items
self._max_items = max_items
self._unique_items = unique_items
def from_params(self, service, params):
self._do_validate(params, "input")
return [
super(PydanticModelList, self).from_params(service, param)
for param in params
]
def to_response(self, service, result):
self._do_validate(result, "output")
return [
super(PydanticModelList, self).to_response(service=service, result=r)
for r in result
]
def to_openapi_query_parameters(self, service, spec):
raise NotImplementedError("List are not (?yet?) supported as query paramters")
def _do_validate(self, values, direction):
ExceptionClass = UserError if direction == "input" else SystemError
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)
)
)
# TODO, we should probably get the spec as parameters. That should
# allows to add the definition of a schema only once into the specs
# and use a reference to the schema into the parameters
def to_openapi_requestbody(self, service, spec):
return {
"content": {
"application/json": {
"schema": self.to_json_schema(service, spec, "input")
}
}
}
def to_openapi_responses(self, service, spec):
return {
"200": {
"content": {
"application/json": {
"schema": self.to_json_schema(service, spec, "output")
}
}
}
}
def to_json_schema(self, service, spec, direction):
json_schema = super().to_json_schema(service, spec, direction)
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
restapi.PydanticModel = PydanticModel
restapi.PydanticModelList = PydanticModelList