Debian Codegraph @

flasgger/utils.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # coding: utf-8
2
3 import codecs
4 import copy
5 import importlib
6 import inspect
7 import os
8 import re
9 import sys
10 import jsonschema
11 import yaml
12 from six import string_types, text_type
13 from copy import deepcopy
14 from functools import wraps
15 from importlib import import_module
16 from collections import OrderedDict, defaultdict
17 from flask import Response
18 from flask import abort
19 from flask import current_app
20 from flask import request
21 from flask.views import MethodView
22
23 try:
24 from flask_mongorest import methods as fmr_methods
25 except ImportError:
26 fmr_methods = None
27
28 from .constants import OPTIONAL_FIELDS, DEFAULT_FIELDS
29 from .marshmallow_apispec import SwaggerView
30 from .marshmallow_apispec import convert_schemas
31 from .marshmallow_apispec import Schema
32
33
34 def merge_specs(target, source):
35 """
36 Update target dictionary with values from the source, recursively.
37 List items will be merged.
38 """
39
40 for key, value in source.items():
41 if isinstance(value, dict):
42 node = target.setdefault(key, {})
43 merge_specs(node, value)
44 elif isinstance(value, list):
45 node = target.setdefault(key, [])
46 node.extend(value)
47 else:
48 target[key] = value
49
50
51 def get_schema_specs(schema_id, swagger):
52 ignore_verbs = set(
53 swagger.config.get('ignore_verbs', ("HEAD", "OPTIONS")))
54
55 # technically only responses is non-optional
56 optional_fields \
57 = swagger.config.get('optional_fields') or OPTIONAL_FIELDS
58
59 openapi_version = swagger.config.get('openapi')
60
61 with swagger.app.app_context():
62 specs = get_specs(
63 current_app.url_map.iter_rules(), ignore_verbs,
64 optional_fields, swagger.sanitizer, openapi_version)
65
66 swags = (swag for _, verbs in specs for _, swag in verbs
67 if swag is not None)
68
69 for swag in swags:
70 for d in swag.get('parameters', []):
71 d_schema_id = d.get('schema', {}).get('id')
72 if d_schema_id is not None \
73 and d_schema_id.lower() == schema_id.lower():
74 return swag
75
76
77 def get_specs(rules, ignore_verbs, optional_fields, sanitizer,
78 openapi_version, doc_dir=None):
79
80 specs = []
81 for rule in rules:
82 endpoint = current_app.view_functions[rule.endpoint]
83 methods = dict()
84 is_mv = is_valid_method_view(endpoint)
85
86 for verb in rule.methods.difference(ignore_verbs):
87 if not is_mv and has_valid_dispatch_view_docs(endpoint):
88 endpoint.methods = endpoint.methods or ['GET']
89 if verb in endpoint.methods:
90 methods[verb.lower()] = endpoint
91 elif getattr(endpoint, 'methods', None) is not None:
92 if isinstance(endpoint.methods, set):
93 if verb in endpoint.methods:
94 verb = verb.lower()
95 methods[verb] = getattr(endpoint.view_class, verb)
96 elif fmr_methods is not None: # flask-mongorest
97 endpoint_methods = set(m.method for m in endpoint.methods)
98 if verb in endpoint_methods:
99 proxy_verb = rule.endpoint.replace(
100 endpoint.__name__, ''
101 )
102 if proxy_verb:
103 methods[verb.lower()] = getattr(
104 fmr_methods, proxy_verb
105 )
106 else:
107 raise TypeError
108 else:
109 methods[verb.lower()] = endpoint
110
111 verbs = []
112 for verb, method in methods.items():
113
114 klass = method.__dict__.get('view_class', None)
115 if not is_mv and klass and hasattr(klass, 'verb'):
116 method = getattr(klass, 'verb', None)
117 elif klass and hasattr(klass, 'dispatch_request'):
118 method = getattr(klass, 'dispatch_request', None)
119 if method is None: # for MethodView
120 method = getattr(klass, verb, None)
121
122 if method is None:
123 if is_mv: # #76 Empty MethodViews
124 continue
125 raise RuntimeError(
126 'Cannot detect view_func for rule {0}'.format(rule)
127 )
128
129 swag = {}
130 swag_def = {}
131
132 swagged = False
133
134 if getattr(method, 'specs_dict', None):
135 definition = {}
136 merge_specs(
137 swag,
138 convert_schemas(deepcopy(method.specs_dict), definition)
139 )
140 swag_def = definition
141 swagged = True
142
143 view_class = getattr(endpoint, 'view_class', None)
144 if view_class and issubclass(view_class, SwaggerView):
145 apispec_swag = {}
146
147 # Don't need to alter definitions here
148 # Since it only stays in apispec_attrs
149 apispec_attrs = optional_fields + [
150 'parameters', 'definitions', 'responses',
151 'summary', 'description'
152 ]
153 for attr in apispec_attrs:
154 value = getattr(view_class, attr)
155 if value:
156 apispec_swag[attr] = value
157 # Don't need to change 'definitions' here
158 # Since it would be appended later according to openapi
159 apispec_definitions = apispec_swag.get('definitions', {})
160 swag.update(
161 convert_schemas(apispec_swag, apispec_definitions)
162 )
163 swag_def = apispec_definitions
164
165 swagged = True
166
167 if doc_dir:
168 if view_class:
169 file_path = os.path.join(
170 doc_dir, endpoint.__name__, method.__name__ + '.yml')
171 else:
172 file_path = os.path.join(
173 doc_dir, endpoint.__name__ + '.yml')
174 if os.path.isfile(file_path):
175 func = method.__func__ \
176 if hasattr(method, '__func__') else method
177 setattr(func, 'swag_type', 'yml')
178 setattr(func, 'swag_path', file_path)
179
180 doc_summary, doc_description, doc_swag = parse_docstring(
181 method, sanitizer, endpoint=rule.endpoint, verb=verb)
182
183 if is_openapi3(openapi_version):
184 swag.setdefault('components', {})['schemas'] = swag_def
185 else: # openapi2
186 swag['definitions'] = swag_def
187
188 if doc_swag:
189 merge_specs(swag, doc_swag)
190 swagged = True
191
192 if swagged:
193 if doc_summary:
194 swag['summary'] = doc_summary
195
196 if doc_description:
197 swag['description'] = doc_description
198
199 verbs.append((verb, swag))
200
201 if verbs:
202 specs.append((rule, verbs))
203
204 return specs
205
206
207 def swag_from(
208 specs=None, filetype=None, endpoint=None, methods=None,
209 validation=False, schema_id=None, data=None, definition=None,
210 validation_function=None, validation_error_handler=None):
211 """
212 Takes a filename.yml, a dictionary or object and loads swagger specs.
213
214 :param specs: a filepath, a dictionary or an object
215 :param filetype: yml or yaml (json and py to be implemented)
216 :param endpoint: endpoint to build definition name
217 :param methods: method to build method based specs
218 :param validation: perform validation?
219 :param schema_id: Definition id ot name to use for validation
220 :param data: data to validate (default is request.json)
221 :param definition: alias to schema_id
222 :param validation_function:
223 custom validation function which takes the positional
224 arguments: data to be validated at first and schema to validate
225 against at second
226 :param validation_error_handler: custom function to handle
227 exceptions thrown when validating which takes the exception
228 thrown as the first, the data being validated as the second and
229 the schema being used to validate as the third argument
230 """
231
232 def resolve_path(function, filepath):
233 try:
234 from pathlib import Path
235 if isinstance(filepath, Path):
236 filepath = str(filepath)
237 except ImportError:
238 pass
239 if not filepath.startswith('/'):
240 if not hasattr(function, 'root_path'):
241 function.root_path = get_root_path(function)
242 res = os.path.join(function.root_path, filepath)
243 return res
244 return filepath
245
246 def set_from_filepath(function):
247 final_filepath = resolve_path(function, specs)
248 function.swag_type = filetype or final_filepath.split('.')[-1]
249
250 if endpoint or methods:
251 if not hasattr(function, 'swag_paths'):
252 function.swag_paths = {}
253
254 if not endpoint and not methods:
255 function.swag_path = final_filepath
256 elif endpoint and methods:
257 for verb in methods:
258 key = "{}_{}".format(endpoint, verb.lower())
259 function.swag_paths[key] = final_filepath
260 elif endpoint and not methods:
261 function.swag_paths[endpoint] = final_filepath
262 elif methods and not endpoint:
263 for verb in methods:
264 function.swag_paths[verb.lower()] = final_filepath
265
266 def set_from_specs_dict(function):
267 function.specs_dict = specs
268
269 def is_path(specs):
270 """ Returns True if specs is a string or pathlib.Path
271 """
272 is_str_path = isinstance(specs, string_types)
273 try:
274 from pathlib import Path
275 is_py3_path = isinstance(specs, Path)
276 return is_str_path or is_py3_path
277 except ImportError:
278 return is_str_path
279
280 def decorator(function):
281
282 if is_path(specs):
283 set_from_filepath(function)
284 # function must have or a single swag_path or a list of them
285 swag_path = getattr(function, 'swag_path', None)
286 swag_paths = getattr(function, 'swag_paths', None)
287 validate_args = {
288 'filepath': swag_path or swag_paths,
289 'root': getattr(function, 'root_path', None)
290 }
291 if isinstance(specs, dict):
292 set_from_specs_dict(function)
293 validate_args = {'specs': specs}
294
295 @wraps(function)
296 def wrapper(*args, **kwargs):
297 if validation is True:
298 validate(
299 data,
300 schema_id or definition,
301 validation_function=validation_function,
302 validation_error_handler=validation_error_handler,
303 **validate_args
304 )
305 return function(*args, **kwargs)
306 return wrapper
307
308 return decorator
309
310
311 def __replace_ref(schema, relative_path, swag):
312 """ TODO: add dev docs
313
314 :param schema:
315 :param relative_path:
316 :param swag:
317 :return:
318 """
319 absolute_path = os.path.dirname(sys.argv[0])
320 new_value = {}
321 for key, value in schema.items():
322 if isinstance(value, dict):
323 new_value[key] = __replace_ref(value, relative_path, swag)
324 elif key == '$ref':
325 # see:
326 # https://swagger.io/docs/specification/describing-request-body/
327 if len(value) > 2 and value.startswith('#/'): # $ref is local
328 content = swag
329 for id in value.split('/')[1:]:
330 content = content[id]
331 return __replace_ref(content, relative_path, swag) \
332 if isinstance(content, dict) else content
333
334 if len(value) > 0 and value[0] == '/':
335 file_ref_path = absolute_path + value
336 else:
337 file_ref_path = relative_path + '/' + value
338 relative_path = os.path.dirname(file_ref_path)
339 with open(file_ref_path) as file:
340 file_content = file.read()
341 comment_index = file_content.rfind('---')
342 if comment_index > 0:
343 comment_index = comment_index + 3
344 else:
345 comment_index = 0
346 content = yaml.safe_load((file_content[comment_index:]))
347 new_value = content
348 if isinstance(content, dict):
349 new_value = __replace_ref(content, relative_path, swag)
350 else:
351 new_value[key] = value
352 return new_value
353
354
355 def validate(
356 data=None, schema_id=None, filepath=None, root=None, definition=None,
357 specs=None, validation_function=None, validation_error_handler=None,
358 require_data=True, openapi_version=None):
359 """
360 This method is available to use YAML swagger definitions file
361 or specs (dict or object) to validate data against its jsonschema.
362
363 example:
364 validate({"item": 1}, 'item_schema', 'defs.yml', root=__file__)
365 validate(request.json, 'User', specs={'definitions': {'User': ...}})
366
367 :param data: data to validate, by default is request.json
368 :param schema_id: The definition id to use to validate (from specs)
369 :param filepath: definition filepath to load specs
370 :param root: root folder (inferred if not provided), unused if path
371 starts with `/`
372 :param definition: Alias to schema_id (kept for backwards
373 compatibility)
374 :param specs: load definitions from dict or object passed here
375 instead of a file.
376 :param validation_function: custom validation function which takes
377 the positional arguments: data to be validated at first and
378 schema to validate against at second
379 :param validation_error_handler: custom function to handle
380 exceptions thrown when validating which takes the exception
381 thrown as the first, the data being validated as the second and
382 the schema being used to validate as the third argument
383 :param require_data: is the data param required?
384 """
385 schema_id = schema_id or definition
386
387 # for backwards compatibility with function signature
388 if filepath is None and specs is None:
389 abort(Response('Filepath or specs is needed to validate', status=500))
390
391 if data is None:
392 data = request.json # defaults
393 elif callable(data):
394 # data=lambda: request.json
395 data = data()
396
397 if not data and require_data:
398 abort(Response('No data to validate', status=400))
399
400 # not used anymore but kept to reuse with marshmallow
401 endpoint = request.endpoint.lower().replace('.', '_')
402 verb = request.method.lower()
403
404 if filepath is not None:
405 if not root:
406 try:
407 frame_info = inspect.stack()[1]
408 root = os.path.dirname(os.path.abspath(frame_info[1]))
409 except Exception:
410 root = None
411 else:
412 root = os.path.dirname(root)
413
414 if not filepath.startswith('/'):
415 final_filepath = os.path.join(root, filepath)
416 else:
417 final_filepath = filepath
418 full_doc = load_from_file(final_filepath)
419 yaml_start = full_doc.find('---')
420 swag = yaml.safe_load(full_doc[yaml_start if yaml_start >= 0 else 0:])
421 else:
422 swag = copy.deepcopy(specs)
423
424 params = [
425 item for item in swag.get('parameters', [])
426 if item.get('schema')
427 ]
428
429 definitions = {}
430 main_def = {}
431 raw_definitions = extract_definitions(params, endpoint=endpoint, verb=verb,
432 openapi_version=openapi_version)
433
434 if schema_id is None:
435 for param in params:
436 if param.get('in') == 'body':
437 schema_id = param.get('schema', {}).get('$ref')
438 if schema_id:
439 schema_id = schema_id.split('/')[-1]
440 break # consider only the first
441
442 if schema_id is None:
443 # if it is still none use first raw_definition extracted
444 if raw_definitions:
445 schema_id = raw_definitions[0].get('id')
446
447 for defi in raw_definitions:
448 if defi['id'].lower() == schema_id.lower():
449 main_def = defi.copy()
450 else:
451 definitions[defi['id']] = defi
452
453 # support definitions informed in dict
454 if schema_id in extract_schema(swag):
455 main_def = extract_schema(swag).get(schema_id)
456
457 # Doensn't need to alter 'definitions' according to open api
458 # Since it main_def exists only in this function
459 main_def['definitions'] = definitions
460
461 for key, value in definitions.items():
462 if 'id' in value:
463 del value['id']
464
465 if validation_function is None:
466 validation_function = jsonschema.validate
467
468 absolute_path = os.path.dirname(sys.argv[0])
469 if filepath is None:
470 relative_path = absolute_path
471 else:
472 relative_path = os.path.dirname(filepath)
473 main_def = __replace_ref(main_def, relative_path, swag)
474
475 try:
476 validation_function(data, main_def)
477 except Exception as err:
478 if validation_error_handler is not None:
479 validation_error_handler(err, data, main_def)
480 else:
481 abort(Response(str(err), status=400))
482
483
484 def apispec_to_template(app, spec, definitions=None, paths=None):
485 """
486 Converts apispec object in to flasgger definitions template
487 :param app: Current app
488 :param spec: apispec.APISpec
489 :param definitions: a list of [Schema, ..] or [('Name', Schema), ..]
490 :param paths: A list of flask views
491 """
492 definitions = definitions or []
493 paths = paths or []
494
495 with app.app_context():
496 for definition in definitions:
497 if isinstance(definition, (tuple, list)):
498 name, schema = definition
499 else:
500 schema = definition
501 name = schema.__name__.replace('Schema', '')
502
503 spec.components.schema(name, schema=schema)
504
505 for path in paths:
506 spec.path(view=path)
507
508 spec_dict = spec.to_dict()
509 ret = ordered_dict_to_dict(spec_dict)
510 return ret
511
512
513 def ordered_dict_to_dict(d):
514 """
515 Converts inner OrderedDict to bare dict
516 """
517 ret = {}
518 new_d = deepcopy(d)
519 for k, v in new_d.items():
520 if isinstance(v, OrderedDict):
521 v = dict(v)
522 if isinstance(v, dict):
523 v = ordered_dict_to_dict(v)
524 ret[k] = v
525 return ret
526
527
528 def remove_suffix(fpath): # pragma: no cover
529 """Remove all file ending suffixes"""
530 return os.path.splitext(fpath)[0]
531
532
533 def is_python_file(fpath): # pragma: no cover
534 """Naive Python module filterer"""
535 return fpath.endswith(".py") and "__" not in fpath
536
537
538 def pathify(basenames, examples_dir="examples/"): # pragma: no cover
539 """*nix to python module path"""
540 example = examples_dir.replace("/", ".")
541 return [example + basename for basename in basenames]
542
543
544 def get_examples(examples_dir="examples/"): # pragma: no cover
545 """All example modules"""
546 all_files = os.listdir(examples_dir)
547 python_files = [f for f in all_files if is_python_file(f)]
548 basenames = [remove_suffix(f) for f in python_files]
549 modules = [import_module(module) for module in pathify(basenames)]
550 return [
551 module for module in modules
552 if getattr(module, 'app', None) is not None
553 ]
554
555
556 def get_path_from_doc(full_doc):
557 """
558 If `file:` is provided import the file.
559 """
560 swag_path = full_doc.replace('file:', '').strip()
561 swag_type = swag_path.split('.')[-1]
562 return swag_path, swag_type
563
564
565 def json_to_yaml(content):
566 """
567 TODO: convert json to yaml
568 """
569 return content
570
571
572 def load_from_file(swag_path, swag_type='yml', root_path=None):
573 """
574 Load specs from YAML file
575 """
576 if swag_type not in ('yaml', 'yml'):
577 raise AttributeError("Currently only yaml or yml supported")
578 # TODO: support JSON
579
580 try:
581 enc = detect_by_bom(swag_path)
582 with codecs.open(swag_path, encoding=enc) as yaml_file:
583 return yaml_file.read()
584 except IOError:
585 # not in the same dir, add dirname
586 swag_path = os.path.join(
587 root_path or os.path.dirname(__file__), swag_path
588 )
589 try:
590 enc = detect_by_bom(swag_path)
591 with codecs.open(swag_path, encoding=enc) as yaml_file:
592 return yaml_file.read()
593 except IOError: # pragma: no cover
594 # if package dir
595 # see https://github.com/rochacbruno/flasgger/pull/104
596 # Still not able to reproduce this case
597 # test are in examples/package_example
598 # need more detail on how to reproduce IOError here
599 swag_path = swag_path.replace("/", os.sep).replace("\\", os.sep)
600 path = swag_path.replace(
601 (root_path or os.path.dirname(__file__)), ''
602 ).split(os.sep)[1:]
603 package_spec = importlib.util.find_spec(path[0])
604 if package_spec.has_location:
605 # Improvement idea: Use package_spec.submodule_search_locations
606 # if we're sure there's only going to be one search location.
607 site_package = package_spec.origin.replace('/__init__.py', '')
608 else:
609 raise RuntimeError("Package does not have origin")
610 swag_path = os.path.join(site_package, os.sep.join(path[1:]))
611 with open(swag_path) as yaml_file:
612 return yaml_file.read()
613
614
615 def detect_by_bom(path, default='utf-8'):
616 with open(path, 'rb') as f:
617 raw = f.read(4) # will read less if the file is smaller
618 for enc, boms in \
619 ('utf-8-sig', (codecs.BOM_UTF8,)),\
620 ('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),\
621 ('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
622 if any(raw.startswith(bom) for bom in boms):
623 return enc
624 return default
625
626
627 def parse_docstring(obj, process_doc, endpoint=None, verb=None):
628 """
629 Gets swag data for method/view docstring
630 """
631 first_line, other_lines, swag = None, None, None
632
633 full_doc = None
634 swag_path = getattr(obj, 'swag_path', None)
635 swag_type = getattr(obj, 'swag_type', 'yml')
636 swag_paths = getattr(obj, 'swag_paths', None)
637 root_path = get_root_path(obj)
638 from_file = False
639
640 if swag_path is not None:
641 full_doc = load_from_file(swag_path, swag_type)
642 from_file = True
643 elif swag_paths is not None:
644 for key in ("{}_{}".format(endpoint, verb), endpoint, verb.lower()):
645 if key in swag_paths:
646 full_doc = load_from_file(swag_paths[key], swag_type)
647 break
648 from_file = True
649 # TODO: handle multiple root_paths
650 # to support `import: ` from multiple places
651 else:
652 full_doc = inspect.getdoc(obj)
653
654 if full_doc:
655
656 if full_doc.startswith('file:'):
657 if not hasattr(obj, 'root_path'):
658 obj.root_path = root_path
659 swag_path, swag_type = get_path_from_doc(full_doc)
660 doc_filepath = os.path.join(obj.root_path, swag_path)
661 full_doc = load_from_file(doc_filepath, swag_type)
662 from_file = True
663
664 full_doc = parse_imports(full_doc, root_path)
665
666 yaml_sep = full_doc.find('---')
667
668 if yaml_sep != -1:
669 line_feed = full_doc.find('\n')
670 if line_feed != -1:
671 first_line = process_doc(full_doc[:line_feed])
672 other_lines = process_doc(
673 full_doc[line_feed + 1: yaml_sep]
674 )
675 swag = yaml.safe_load(full_doc[yaml_sep + 4:])
676 else:
677 if from_file:
678 swag = yaml.safe_load(full_doc)
679 else:
680 first_line = full_doc
681
682 return first_line, other_lines, swag
683
684
685 def get_root_path(obj):
686 """
687 Get file path for object and returns its dirname
688 """
689 try:
690 filename = os.path.abspath(obj.__globals__['__file__'])
691 except (KeyError, AttributeError):
692 if getattr(obj, '__wrapped__', None):
693 # decorator package has been used in view
694 return get_root_path(obj.__wrapped__)
695 filename = inspect.getfile(obj)
696 return os.path.dirname(filename)
697
698
699 def parse_definition_docstring(obj, process_doc):
700 """
701 Gets swag data from docstring for class based definitions
702 """
703 doc_lines, swag = None, None
704
705 full_doc = None
706 swag_path = getattr(obj, 'swag_path', None)
707 swag_type = getattr(obj, 'swag_type', 'yml')
708
709 if swag_path is not None:
710 full_doc = load_from_file(swag_path, swag_type)
711 else:
712 full_doc = inspect.getdoc(obj)
713
714 if full_doc:
715
716 if full_doc.startswith('file:'):
717 if not hasattr(obj, 'root_path'):
718 obj.root_path = get_root_path(obj)
719 swag_path, swag_type = get_path_from_doc(full_doc)
720 doc_filepath = os.path.join(obj.root_path, swag_path)
721 full_doc = load_from_file(doc_filepath, swag_type)
722
723 yaml_sep = full_doc.find('---')
724 if yaml_sep != -1:
725 doc_lines = process_doc(
726 full_doc[:yaml_sep - 1]
727 ) if yaml_sep else None
728 swag = yaml.safe_load(full_doc[yaml_sep:])
729 else:
730 doc_lines = process_doc(full_doc)
731
732 return doc_lines, swag
733
734
735 def parse_imports(full_doc, root_path=None):
736 """
737 Supports `import: otherfile.yml` in docstring specs
738 """
739 regex = re.compile('import: "(.*)"')
740 import_prop = regex.search(full_doc)
741 if import_prop:
742 start = import_prop.start()
743 spaces_num = start - full_doc.rfind('\n', 0, start) - 1
744 filepath = import_prop.group(1)
745 if filepath.startswith('/'):
746 imported_doc = load_from_file(filepath)
747 else:
748 imported_doc = load_from_file(filepath, root_path=root_path)
749 indented_imported_doc = imported_doc.replace(
750 '\n', '\n' + ' ' * spaces_num
751 )
752 full_doc = regex.sub(indented_imported_doc, full_doc, count=1)
753 return parse_imports(full_doc)
754 return full_doc
755
756
757 def extract_definitions(alist, level=None, endpoint=None, verb=None,
758 prefix_ids=False, openapi_version=None):
759 """
760 Since we couldn't be bothered to register models elsewhere
761 our definitions need to be extracted from the parameters.
762 We require an 'id' field for the schema to be correctly
763 added to the definitions list.
764 """
765 endpoint = endpoint or request.endpoint.lower()
766 verb = verb or request.method.lower()
767 endpoint = endpoint.replace('.', '_')
768
769 def _extract_array_defs(source):
770 """
771 Extracts definitions identified by `id`
772 """
773 # extract any definitions that are within arrays
774 # this occurs recursively
775 ret = []
776 items = source.get('items')
777 if items is not None and 'schema' in items:
778 ret += extract_definitions(
779 [items], level + 1, endpoint, verb, prefix_ids,
780 openapi_version)
781 return ret
782
783 # for tracking level of recursion
784 if level is None:
785 level = 0
786
787 defs = list()
788 for item in alist:
789 if not getattr(item, 'get'):
790 raise RuntimeError('definitions must be a list of dicts')
791 schema = item.get("schema")
792 if schema is not None:
793 schema_id = schema.get("id")
794 if schema_id is not None:
795 # add endpoint_verb to schema id to avoid conflicts
796 if prefix_ids:
797 schema['id'] = schema_id = "{}_{}_{}".format(
798 endpoint, verb, schema_id
799 )
800 # ^ api['SWAGGER']['prefix_ids'] = True
801 # ... for backwards compatibility with <= 0.5.14
802
803 defs.append(schema)
804
805 ref_path = None
806 if is_openapi3(openapi_version):
807 ref_path = "#/components/schemas/"
808 else:
809 ref_path = "#/definitions/"
810 ref = {"$ref": "{}{}".format(ref_path, schema_id)}
811
812 # only add the reference as a schema if we are in a
813 # response or a parameter i.e. at the top level
814 # directly ref if a definition is used within another
815 # definition
816 if level == 0:
817 item['schema'] = ref
818 else:
819 item.update(ref)
820 del item['schema']
821
822 # extract any definitions that are within properties
823 # this occurs recursively
824 properties = schema.get('properties')
825 if properties is not None:
826 defs += extract_definitions(
827 properties.values(), level + 1, endpoint, verb, prefix_ids,
828 openapi_version)
829
830 defs += _extract_array_defs(schema)
831
832 defs += _extract_array_defs(item)
833
834 return defs
835
836
837 def has_valid_dispatch_view_docs(endpoint):
838 """
839 Return True if dispatch_request is swaggable
840 """
841 klass = endpoint.__dict__.get('view_class', None)
842 return klass and hasattr(klass, 'dispatch_request') \
843 and hasattr(endpoint, 'methods') \
844 and getattr(klass, 'dispatch_request').__doc__
845
846
847 def is_valid_method_view(endpoint):
848 """
849 Return True if obj is MethodView
850 """
851 klass = endpoint.__dict__.get('view_class', None)
852 try:
853 return issubclass(klass, MethodView)
854 except TypeError:
855 return False
856
857
858 def get_vendor_extension_fields(mapping):
859 """
860 Identify vendor extension fields and extract them into a new dictionary.
861 Examples:
862 >>> get_vendor_extension_fields({'test': 1})
863 {}
864 >>> get_vendor_extension_fields({'test': 1, 'x-test': 2})
865 {'x-test': 2}
866 """
867 return {k: v for k, v in mapping.items() if k.startswith('x-')}
868
869
870 class StringLike(object):
871 """
872 Class to mimic the behavior of a regular string. Classes that inherit (or
873 mixin) this class must implement the `__str__` magic method. Whatever that
874 method returns is used by the various string-like methods.
875 """
876
877 def __getattr__(self, attr):
878 """
879 Forwards any non-magic methods to the resulting string's class. This
880 allows support for string methods like `upper()`, `lower()`, etc.
881 """
882 string = self.text_type(self)
883 if hasattr(string, attr):
884 return getattr(string, attr)
885 raise AttributeError(attr)
886
887 def __len__(self):
888 return len(self.text_type(self))
889
890 def __getitem__(self, key):
891 return self.text_type(self)[key]
892
893 def __iter__(self):
894 return iter(self.text_type(self))
895
896 def __contains__(self, item):
897 return item in self.text_type(self)
898
899 def __add__(self, other):
900 return self.text_type(self) + other
901
902 def __radd__(self, other):
903 return other + self.text_type(self)
904
905 def __mul__(self, other):
906 return self.text_type(self) * other
907
908 def __rmul__(self, other):
909 return other * self.text_type(self)
910
911 def __lt__(self, other):
912 return self.text_type(self) < other
913
914 def __le__(self, other):
915 return self.text_type(self) <= other
916
917 def __eq__(self, other):
918 return self.text_type(self) == other
919
920 def __ne__(self, other):
921 return self.text_type(self) != other
922
923 def __gt__(self, other):
924 return self.text_type(self) > other
925
926 def __ge__(self, other):
927 return self.text_type(self) >= other
928
929 @property
930 def text_type(self):
931 return text_type
932
933
934 class LazyString(StringLike):
935 """
936 A lazy string *without* caching. The resulting string is regenerated for
937 every request.
938 """
939
940 def __init__(self, func):
941 """
942 Creates a `LazyString` object using `func` as the delayed closure.
943 `func` must return a string.
944 """
945 self._func = func
946
947 def __str__(self):
948 """
949 Returns the actual string.
950 """
951 return self.text_type(self._func())
952
953
954 class CachedLazyString(LazyString):
955 """
956 A lazy string with caching.
957 """
958
959 def __init__(self, func):
960 """
961 Uses `__init__()` from the parent and initializes a cache.
962 """
963 super(CachedLazyString, self).__init__(func)
964 self._cache = None
965
966 def __str__(self):
967 """
968 Returns the actual string and caches the result.
969 """
970 if not self._cache:
971 self._cache = self.text_type(self._func())
972 return self._cache
973
974
975 def swag_annotation(f):
976 @wraps(f)
977 def wrapper(*args, **kwargs):
978
979 if not kwargs.pop("swag", False):
980 return f(*args, **kwargs)
981
982 function = args[2]
983
984 specs = {}
985 for key, value in DEFAULT_FIELDS.items():
986 specs[key] = kwargs.pop(key, value)
987
988 for variable, annotation in function.__annotations__.items():
989
990 if issubclass(annotation, Schema):
991 annotation = annotation()
992 data = annotation.to_specs_dict()
993
994 for row in data["parameters"]:
995 specs["parameters"].append(row)
996 specs["definitions"].update(data["definitions"])
997
998 function = validate_annotation(annotation, variable)(function)
999
1000 elif issubclass(annotation, int):
1001 m = {"name": variable,
1002 "in": "path",
1003 "type": "integer",
1004 "required": True}
1005 if ("int(signed=True):" + variable) in args[0]:
1006 m['minimum'] = 0
1007 specs["parameters"].append(m)
1008
1009 elif issubclass(annotation, str):
1010 specs["parameters"].append({"name": variable,
1011 "in": "path",
1012 "type": "string",
1013 "required": True})
1014
1015 function.specs_dict = specs
1016 args = list(args)
1017 args[2] = function
1018 args = tuple(args)
1019
1020 return f(*args, **kwargs)
1021 return wrapper
1022
1023
1024 def validate_annotation(an, var):
1025 def decorator(f):
1026 @wraps(f)
1027 def wrapper(*args, **kwargs):
1028
1029 if an.swag_validate:
1030
1031 payload = None
1032
1033 if an.swag_in == "query":
1034 payload = dict(request.args)
1035
1036 elif an.swag_in == "body" and request.is_json:
1037 payload = request.json
1038
1039 validate(
1040 payload,
1041 specs=an.to_specs_dict(),
1042 validation_function=an.swag_validation_function,
1043 validation_error_handler=an.swag_validation_error_handler,
1044 require_data=an.swag_require_data
1045 # handle openapiversion later
1046 )
1047
1048 return f(*args, **kwargs, **{var: payload})
1049 return wrapper
1050 return decorator
1051
1052
1053 def is_openapi3(openapi_version):
1054 """
1055 Returns True if openapi_version is 3
1056 """
1057 return openapi_version and str(openapi_version).split('.')[0] == '3'
1058
1059
1060 def extract_schema(spec: dict) -> defaultdict:
1061 """
1062 Returns schema resources according to openapi version
1063 """
1064 openapi_version = spec.get('openapi', None)
1065 if is_openapi3(openapi_version):
1066 return spec.get('components', {}
1067 ).get('schemas', defaultdict(dict))
1068 else: # openapi2
1069 return spec.get('definitions', defaultdict(dict))