-
-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathmodels.py
657 lines (561 loc) · 25.2 KB
/
models.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
"""OpenAPI core schemas models module"""
import attr
import functools
import logging
from collections import defaultdict
from datetime import date, datetime
from uuid import UUID
import re
import warnings
from six import iteritems, integer_types, binary_type, text_type
from openapi_core.extensions.models.factories import ModelFactory
from openapi_core.schema.schemas.enums import SchemaFormat, SchemaType
from openapi_core.schema.schemas.exceptions import (
InvalidSchemaValue, UndefinedSchemaProperty, MissingSchemaProperty,
OpenAPISchemaError, NoOneOfSchema, MultipleOneOfSchema, NoValidSchema,
UndefinedItemsSchema, InvalidCustomFormatSchemaValue, InvalidSchemaProperty,
UnmarshallerStrictTypeError,
)
from openapi_core.schema.schemas.util import (
forcebool, format_date, format_datetime, format_byte, format_uuid,
format_number,
)
from openapi_core.schema.schemas.validators import (
TypeValidator, AttributeValidator,
)
log = logging.getLogger(__name__)
@attr.s
class Format(object):
unmarshal = attr.ib()
validate = attr.ib()
class Schema(object):
"""Represents an OpenAPI Schema."""
DEFAULT_CAST_CALLABLE_GETTER = {
}
STRING_FORMAT_CALLABLE_GETTER = {
SchemaFormat.NONE: Format(text_type, TypeValidator(text_type)),
SchemaFormat.PASSWORD: Format(text_type, TypeValidator(text_type)),
SchemaFormat.DATE: Format(
format_date, TypeValidator(date, exclude=datetime)),
SchemaFormat.DATETIME: Format(format_datetime, TypeValidator(datetime)),
SchemaFormat.BINARY: Format(binary_type, TypeValidator(binary_type)),
SchemaFormat.UUID: Format(format_uuid, TypeValidator(UUID)),
SchemaFormat.BYTE: Format(format_byte, TypeValidator(text_type)),
}
NUMBER_FORMAT_CALLABLE_GETTER = {
SchemaFormat.NONE: Format(format_number, TypeValidator(
integer_types + (float, ), exclude=bool)),
SchemaFormat.FLOAT: Format(float, TypeValidator(float)),
SchemaFormat.DOUBLE: Format(float, TypeValidator(float)),
}
TYPE_VALIDATOR_CALLABLE_GETTER = {
SchemaType.ANY: lambda x: True,
SchemaType.BOOLEAN: TypeValidator(bool),
SchemaType.INTEGER: TypeValidator(integer_types, exclude=bool),
SchemaType.NUMBER: TypeValidator(
integer_types + (float, ), exclude=bool),
SchemaType.STRING: TypeValidator(
text_type, date, datetime, binary_type, UUID),
SchemaType.ARRAY: TypeValidator(list, tuple),
SchemaType.OBJECT: AttributeValidator('__dict__'),
}
def __init__(
self, schema_type=None, model=None, properties=None, items=None,
schema_format=None, required=None, default=None, nullable=False,
enum=None, deprecated=False, all_of=None, one_of=None,
additional_properties=True, min_items=None, max_items=None,
min_length=None, max_length=None, pattern=None, unique_items=False,
minimum=None, maximum=None, multiple_of=None,
exclusive_minimum=False, exclusive_maximum=False,
min_properties=None, max_properties=None):
self.type = SchemaType(schema_type)
self.model = model
self.properties = properties and dict(properties) or {}
self.items = items
self.format = schema_format
self.required = required or []
self.default = default
self.nullable = nullable
self.enum = enum
self.deprecated = deprecated
self.all_of = all_of and list(all_of) or []
self.one_of = one_of and list(one_of) or []
self.additional_properties = additional_properties
self.min_items = int(min_items) if min_items is not None else None
self.max_items = int(max_items) if max_items is not None else None
self.min_length = int(min_length) if min_length is not None else None
self.max_length = int(max_length) if max_length is not None else None
self.pattern = pattern and re.compile(pattern) or None
self.unique_items = unique_items
self.minimum = int(minimum) if minimum is not None else None
self.maximum = int(maximum) if maximum is not None else None
self.multiple_of = int(multiple_of)\
if multiple_of is not None else None
self.exclusive_minimum = exclusive_minimum
self.exclusive_maximum = exclusive_maximum
self.min_properties = int(min_properties)\
if min_properties is not None else None
self.max_properties = int(max_properties)\
if max_properties is not None else None
self._all_required_properties_cache = None
self._all_optional_properties_cache = None
def __getitem__(self, name):
return self.properties[name]
def get_all_properties(self):
properties = self.properties.copy()
for subschema in self.all_of:
subschema_props = subschema.get_all_properties()
properties.update(subschema_props)
return properties
def get_all_properties_names(self):
all_properties = self.get_all_properties()
return set(all_properties.keys())
def get_all_required_properties(self):
if self._all_required_properties_cache is None:
self._all_required_properties_cache =\
self._get_all_required_properties()
return self._all_required_properties_cache
def _get_all_required_properties(self):
all_properties = self.get_all_properties()
required = self.get_all_required_properties_names()
return dict(
(prop_name, val)
for prop_name, val in iteritems(all_properties)
if prop_name in required
)
def get_all_required_properties_names(self):
required = self.required[:]
for subschema in self.all_of:
subschema_req = subschema.get_all_required_properties()
required += subschema_req
return set(required)
def get_cast_mapping(self, custom_formatters=None, strict=True,
require_all_props=False):
primitive_unmarshallers = self.get_primitive_unmarshallers(
custom_formatters=custom_formatters,
require_all_props=require_all_props
)
primitive_unmarshallers_partial = dict(
(t, functools.partial(
u,
type_format=self.format,
strict=strict,
require_all_props=require_all_props)
)
for t, u in primitive_unmarshallers.items()
)
complex_unmarshallers = {
SchemaType.ANY: self._unmarshal_any,
SchemaType.ARRAY: self._unmarshal_collection,
SchemaType.OBJECT: self._unmarshal_object,
}
complex_unmarshallers_partial = dict(
(t, functools.partial(
u,
custom_formatters=custom_formatters,
strict=strict,
require_all_props=require_all_props)
)
for t, u in complex_unmarshallers.items()
)
mapping = self.DEFAULT_CAST_CALLABLE_GETTER.copy()
mapping.update(primitive_unmarshallers_partial)
mapping.update(complex_unmarshallers_partial)
return defaultdict(lambda: lambda x: x, mapping)
def are_additional_properties_allowed(self, one_of_schema=None):
return (
(self.additional_properties is not False) and
(one_of_schema is None or
one_of_schema.additional_properties is not False)
)
def cast(self, value, custom_formatters=None, strict=True,
require_all_props=False):
"""Cast value to schema type"""
if value is None:
if not self.nullable:
raise InvalidSchemaValue("Null value for non-nullable schema", value, self.type)
return self.default
if self.enum and value not in self.enum:
raise InvalidSchemaValue(
"Value {value} not in enum choices: {type}", value, self.enum)
cast_mapping = self.get_cast_mapping(
custom_formatters=custom_formatters, strict=strict,
require_all_props=require_all_props)
if self.type is not SchemaType.STRING and value == '':
return None
cast_callable = cast_mapping[self.type]
try:
return cast_callable(value)
except UnmarshallerStrictTypeError:
raise InvalidSchemaValue(
"Value {value} is not of type {type}", value, self.type)
except ValueError:
raise InvalidSchemaValue(
"Failed to cast value {value} to type {type}", value, self.type)
def unmarshal(self, value, custom_formatters=None, strict=True,
require_all_props=False):
"""Unmarshal parameter from the value."""
if self.deprecated:
warnings.warn("The schema is deprecated", DeprecationWarning)
casted = self.cast(value, custom_formatters=custom_formatters, strict=strict,
require_all_props=require_all_props)
if casted is None and not self.required:
return None
return casted
def get_primitive_unmarshallers(self, **options):
from openapi_core.schema.schemas.unmarshallers import (
StringUnmarshaller, BooleanUnmarshaller, IntegerUnmarshaller,
NumberUnmarshaller,
)
unmarshallers_classes = {
SchemaType.STRING: StringUnmarshaller,
SchemaType.BOOLEAN: BooleanUnmarshaller,
SchemaType.INTEGER: IntegerUnmarshaller,
SchemaType.NUMBER: NumberUnmarshaller,
}
unmarshallers = dict(
(t, klass(**options))
for t, klass in unmarshallers_classes.items()
)
return unmarshallers
def _unmarshal_any(self, value, custom_formatters=None, strict=True,
require_all_props=False):
types_resolve_order = [
SchemaType.OBJECT, SchemaType.ARRAY, SchemaType.BOOLEAN,
SchemaType.INTEGER, SchemaType.NUMBER, SchemaType.STRING,
]
cast_mapping = self.get_cast_mapping()
if self.one_of:
result = None
for subschema in self.one_of:
try:
casted = subschema.cast(
value, custom_formatters,
require_all_props=require_all_props
)
except (OpenAPISchemaError, TypeError, ValueError):
continue
else:
if result is not None:
raise MultipleOneOfSchema(self.type)
result = casted
if result is None:
raise NoOneOfSchema(self.type)
return result
else:
for schema_type in types_resolve_order:
cast_callable = cast_mapping[schema_type]
try:
return cast_callable(value)
except UnmarshallerStrictTypeError:
continue
# @todo: remove ValueError when validation separated
except (OpenAPISchemaError, TypeError, ValueError):
continue
raise NoValidSchema(value)
def _unmarshal_collection(self, value, custom_formatters=None, strict=True,
require_all_props=False):
if not isinstance(value, (list, tuple)):
raise InvalidSchemaValue("Value {value} is not of type {type}", value, self.type)
if self.items is None:
raise UndefinedItemsSchema(self.type)
f = functools.partial(
self.items.unmarshal,
custom_formatters=custom_formatters, strict=strict,
require_all_props=require_all_props
)
return list(map(f, value))
def _unmarshal_object(self, value, model_factory=None,
custom_formatters=None, strict=True,
require_all_props=False):
if not isinstance(value, (dict, )):
raise InvalidSchemaValue("Value {value} is not of type {type}", value, self.type)
model_factory = model_factory or ModelFactory()
if self.one_of:
properties = None
for one_of_schema in self.one_of:
try:
found_props = self._unmarshal_properties(
value, one_of_schema, custom_formatters=custom_formatters,
require_all_props=False)
except OpenAPISchemaError:
pass
else:
if properties is not None:
raise MultipleOneOfSchema(self.type)
properties = found_props
if properties is None:
raise NoOneOfSchema(self.type)
else:
properties = self._unmarshal_properties(
value, custom_formatters=custom_formatters,
require_all_props=require_all_props)
return model_factory.create(properties, name=self.model)
def _unmarshal_properties(self, value, one_of_schema=None,
custom_formatters=None, strict=True,
require_all_props=False):
all_props = self.get_all_properties()
all_props_names = self.get_all_properties_names()
all_req_props_names = self.get_all_required_properties_names()
if one_of_schema is not None:
all_props.update(one_of_schema.get_all_properties())
all_props_names |= one_of_schema.\
get_all_properties_names()
all_req_props_names |= one_of_schema.\
get_all_required_properties_names()
value_props_names = value.keys()
extra_props = set(value_props_names) - set(all_props_names)
extra_props_allowed = self.are_additional_properties_allowed(
one_of_schema)
if extra_props and not extra_props_allowed:
raise UndefinedSchemaProperty(extra_props)
properties = {}
if self.additional_properties is not True:
for prop_name in extra_props:
prop_value = value[prop_name]
properties[prop_name] = self.additional_properties.unmarshal(
prop_value,
custom_formatters=custom_formatters,
require_all_props=require_all_props
)
for prop_name, prop in iteritems(all_props):
try:
prop_value = value[prop_name]
except KeyError:
if prop_name in all_req_props_names:
raise MissingSchemaProperty(prop_name)
if not prop.nullable and not prop.default:
continue
prop_value = prop.default
try:
properties[prop_name] = prop.unmarshal(
prop_value,
custom_formatters=custom_formatters,
require_all_props=require_all_props
)
except OpenAPISchemaError as exc:
raise InvalidSchemaProperty(prop_name, exc)
self._validate_properties(properties, one_of_schema=one_of_schema,
custom_formatters=custom_formatters,
require_all_props=require_all_props)
return properties
def get_validator_mapping(self):
mapping = {
SchemaType.ARRAY: self._validate_collection,
SchemaType.STRING: self._validate_string,
SchemaType.OBJECT: self._validate_object,
SchemaType.INTEGER: self._validate_number,
SchemaType.NUMBER: self._validate_number,
}
def default(x, **kw):
return x
return defaultdict(lambda: default, mapping)
def validate(self, value, custom_formatters=None,
require_all_props=False):
if value is None:
if not self.nullable:
raise InvalidSchemaValue("Null value for non-nullable schema of type {type}", value, self.type)
return
# type validation
type_validator_callable = self.TYPE_VALIDATOR_CALLABLE_GETTER[
self.type]
if not type_validator_callable(value):
raise InvalidSchemaValue(
"Value {value} not valid type {type}", value, self.type.value)
# structure validation
validator_mapping = self.get_validator_mapping()
validator_callable = validator_mapping[self.type]
validator_callable(
value,
custom_formatters=custom_formatters,
require_all_props=False
)
return value
def _validate_collection(self, value, custom_formatters=None,
require_all_props=False):
if self.items is None:
raise UndefinedItemsSchema(self.type)
if self.min_items is not None:
if self.min_items < 0:
raise OpenAPISchemaError(
"Schema for collection invalid:"
" minItems must be non-negative"
)
if len(value) < self.min_items:
raise InvalidSchemaValue(
"Value must contain at least {type} item(s),"
" {value} found", len(value), self.min_items)
if self.max_items is not None:
if self.max_items < 0:
raise OpenAPISchemaError(
"Schema for collection invalid:"
" maxItems must be non-negative"
)
if len(value) > self.max_items:
raise InvalidSchemaValue(
"Value must contain at most {value} item(s),"
" {type} found", len(value), self.max_items)
if self.unique_items and len(set(value)) != len(value):
raise OpenAPISchemaError("Value may not contain duplicate items")
f = functools.partial(self.items.validate,
custom_formatters=custom_formatters,
require_all_props=require_all_props)
return list(map(f, value))
def _validate_number(self, value, custom_formatters=None,
require_all_props=False):
if self.minimum is not None:
if self.exclusive_minimum and value <= self.minimum:
raise InvalidSchemaValue(
"Value {value} is not less than or equal to {type}", value, self.minimum)
elif value < self.minimum:
raise InvalidSchemaValue(
"Value {value} is not less than {type}", value, self.minimum)
if self.maximum is not None:
if self.exclusive_maximum and value >= self.maximum:
raise InvalidSchemaValue(
"Value {value} is not greater than or equal to {type}", value, self.maximum)
elif value > self.maximum:
raise InvalidSchemaValue(
"Value {value} is not greater than {type}", value, self.maximum)
if self.multiple_of is not None and value % self.multiple_of:
raise InvalidSchemaValue(
"Value {value} is not a multiple of {type}",
value, self.multiple_of)
def _validate_string(self, value, custom_formatters=None,
require_all_props=False):
try:
schema_format = SchemaFormat(self.format)
except ValueError:
msg = "Unsupported {0} format validation".format(self.format)
if custom_formatters is not None:
formatstring = custom_formatters.get(self.format)
if formatstring is None:
raise OpenAPISchemaError(msg)
else:
raise OpenAPISchemaError(msg)
else:
formatstring =\
self.STRING_FORMAT_CALLABLE_GETTER[schema_format]
if not formatstring.validate(value):
raise InvalidSchemaValue(
"Value {value} not valid format {type}", value, self.format)
if self.min_length is not None:
if self.min_length < 0:
raise OpenAPISchemaError(
"Schema for string invalid:"
" minLength must be non-negative"
)
if len(value) < self.min_length:
raise InvalidSchemaValue(
"Value is shorter ({value}) than the minimum length of {type}",
len(value), self.min_length
)
if self.max_length is not None:
if self.max_length < 0:
raise OpenAPISchemaError(
"Schema for string invalid:"
" maxLength must be non-negative"
)
if len(value) > self.max_length:
raise InvalidSchemaValue(
"Value is longer ({value}) than the maximum length of {type}",
len(value), self.max_length
)
if self.pattern is not None and not self.pattern.search(value):
raise InvalidSchemaValue(
"Value {value} does not match the pattern {type}",
value, self.pattern.pattern
)
return True
def _validate_object(self, value, custom_formatters=None,
require_all_props=False):
properties = value.__dict__
if self.one_of:
valid_one_of_schema = None
for one_of_schema in self.one_of:
try:
self._validate_properties(
properties, one_of_schema,
custom_formatters=custom_formatters,
require_all_props=require_all_props
)
except OpenAPISchemaError:
pass
else:
if valid_one_of_schema is not None:
raise MultipleOneOfSchema(self.type)
valid_one_of_schema = True
if valid_one_of_schema is None:
raise NoOneOfSchema(self.type)
else:
self._validate_properties(
properties,
custom_formatters=custom_formatters,
require_all_props=require_all_props
)
if self.min_properties is not None:
if self.min_properties < 0:
raise OpenAPISchemaError(
"Schema for object invalid:"
" minProperties must be non-negative"
)
if len(properties) < self.min_properties:
raise InvalidSchemaValue(
"Value must contain at least {type} properties,"
" {value} found", len(properties), self.min_properties
)
if self.max_properties is not None:
if self.max_properties < 0:
raise OpenAPISchemaError(
"Schema for object invalid:"
" maxProperties must be non-negative"
)
if len(properties) > self.max_properties:
raise InvalidSchemaValue(
"Value must contain at most {type} properties,"
" {value} found", len(properties), self.max_properties
)
return True
def _validate_properties(self, value, one_of_schema=None,
custom_formatters=None,
require_all_props=False):
all_props = self.get_all_properties()
all_props_names = self.get_all_properties_names()
all_req_props_names = self.get_all_required_properties_names()
if one_of_schema is not None:
all_props.update(one_of_schema.get_all_properties())
all_props_names |= one_of_schema.\
get_all_properties_names()
all_req_props_names |= one_of_schema.\
get_all_required_properties_names()
value_props_names = value.keys()
extra_props = set(value_props_names) - set(all_props_names)
extra_props_allowed = self.are_additional_properties_allowed(
one_of_schema)
if extra_props and not extra_props_allowed:
raise UndefinedSchemaProperty(extra_props)
if self.additional_properties is not True:
for prop_name in extra_props:
prop_value = value[prop_name]
self.additional_properties.validate(
prop_value,
custom_formatters=custom_formatters,
require_all_props=require_all_props
)
for prop_name, prop in iteritems(all_props):
try:
prop_value = value[prop_name]
except KeyError:
if (prop_name in all_req_props_names) or require_all_props:
raise MissingSchemaProperty(prop_name)
if not prop.nullable and not prop.default:
continue
prop_value = prop.default
try:
prop.validate(prop_value,
custom_formatters=custom_formatters,
require_all_props=require_all_props
)
except OpenAPISchemaError as exc:
raise InvalidSchemaProperty(prop_name, original_exception=exc)
return True