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