| 1 |
""" |
| 2 |
What's the big idea? |
| 3 |
|
| 4 |
An endpoint that traverses all restful endpoints producing a swagger 2.0 schema |
| 5 |
If a swagger yaml description is found in the docstrings for an endpoint |
| 6 |
we add the endpoint to swagger specification output |
| 7 |
|
| 8 |
""" |
| 9 |
import re |
| 10 |
import os |
| 11 |
import codecs |
| 12 |
import yaml |
| 13 |
try: |
| 14 |
import simplejson as json |
| 15 |
except ImportError: |
| 16 |
import json |
| 17 |
from functools import wraps, partial |
| 18 |
from collections import defaultdict |
| 19 |
from flask import Blueprint |
| 20 |
from flask import current_app |
| 21 |
from flask import jsonify, Response |
| 22 |
from flask import redirect |
| 23 |
from flask import render_template |
| 24 |
from flask import request, url_for |
| 25 |
from flask import abort |
| 26 |
from flask.views import MethodView |
| 27 |
try: |
| 28 |
from flask.json.provider import DefaultJSONProvider |
| 29 |
except ImportError: |
| 30 |
from flask.json import JSONEncoder as DefaultJSONProvider |
| 31 |
try: |
| 32 |
from flask_restful.reqparse import RequestParser |
| 33 |
except ImportError: |
| 34 |
RequestParser = None |
| 35 |
import jsonschema |
| 36 |
try: |
| 37 |
from markupsafe import Markup |
| 38 |
except ImportError: |
| 39 |
from flask import Markup |
| 40 |
from mistune import markdown |
| 41 |
from .constants import OPTIONAL_FIELDS, OPTIONAL_OAS3_FIELDS |
| 42 |
from .utils import LazyString |
| 43 |
from .utils import extract_definitions |
| 44 |
from .utils import get_schema_specs |
| 45 |
from .utils import get_specs |
| 46 |
from .utils import get_vendor_extension_fields |
| 47 |
from .utils import is_openapi3 |
| 48 |
from .utils import parse_definition_docstring |
| 49 |
from .utils import parse_imports |
| 50 |
from .utils import swag_annotation |
| 51 |
from .utils import validate |
| 52 |
from .utils import extract_schema |
| 53 |
from . import __version__ |
| 54 |
|
| 55 |
|
| 56 |
def NO_SANITIZER(text): |
| 57 |
return text |
| 58 |
|
| 59 |
|
| 60 |
def BR_SANITIZER(text): |
| 61 |
return text.replace('\n', '<br/>') if text else text |
| 62 |
|
| 63 |
|
| 64 |
def MK_SANITIZER(text): |
| 65 |
return Markup(markdown(text)) if text else text |
| 66 |
|
| 67 |
|
| 68 |
class APIDocsView(MethodView): |
| 69 |
""" |
| 70 |
The /apidocs |
| 71 |
""" |
| 72 |
|
| 73 |
def __init__(self, *args, **kwargs): |
| 74 |
view_args = kwargs.pop('view_args', {}) |
| 75 |
self.config = view_args.get('config') |
| 76 |
super(APIDocsView, self).__init__(*args, **kwargs) |
| 77 |
|
| 78 |
def get(self): |
| 79 |
""" |
| 80 |
The data under /apidocs |
| 81 |
json or Swagger UI |
| 82 |
""" |
| 83 |
base_endpoint = self.config.get('endpoint', 'flasgger') |
| 84 |
specs = [ |
| 85 |
{ |
| 86 |
"url": url_for(".".join((base_endpoint, spec['endpoint']))), |
| 87 |
"title": spec.get('title', 'API Spec 1'), |
| 88 |
"name": spec.get('name', None), |
| 89 |
"version": spec.get("version", '0.0.1'), |
| 90 |
"endpoint": spec.get('endpoint') |
| 91 |
} |
| 92 |
for spec in self.config.get('specs', []) |
| 93 |
] |
| 94 |
urls = [ |
| 95 |
{ |
| 96 |
"name": spec["name"], |
| 97 |
"url": spec["url"] |
| 98 |
} |
| 99 |
for spec in specs if spec["name"] |
| 100 |
] |
| 101 |
data = { |
| 102 |
"specs": specs, |
| 103 |
"urls": urls, |
| 104 |
"title": self.config.get('title', 'Flasgger') |
| 105 |
} |
| 106 |
if request.args.get('json'): |
| 107 |
|
| 108 |
return jsonify(data) |
| 109 |
else: |
| 110 |
data['flasgger_config'] = self.config |
| 111 |
data['json'] = json |
| 112 |
data['flasgger_version'] = __version__ |
| 113 |
data['favicon'] = self.config.get( |
| 114 |
'favicon', |
| 115 |
url_for('flasgger.static', filename='favicon-32x32.png') |
| 116 |
) |
| 117 |
data['swagger_ui_bundle_js'] = self.config.get( |
| 118 |
'swagger_ui_bundle_js', |
| 119 |
url_for('flasgger.static', filename='swagger-ui-bundle.js') |
| 120 |
) |
| 121 |
data['swagger_ui_standalone_preset_js'] = self.config.get( |
| 122 |
'swagger_ui_standalone_preset_js', |
| 123 |
url_for('flasgger.static', |
| 124 |
filename='swagger-ui-standalone-preset.js') |
| 125 |
) |
| 126 |
data['jquery_js'] = self.config.get( |
| 127 |
'jquery_js', |
| 128 |
url_for('flasgger.static', filename='lib/jquery.min.js') |
| 129 |
) |
| 130 |
data['swagger_ui_css'] = self.config.get( |
| 131 |
'swagger_ui_css', |
| 132 |
url_for('flasgger.static', filename='swagger-ui.css') |
| 133 |
) |
| 134 |
return render_template( |
| 135 |
'flasgger/index.html', |
| 136 |
**data |
| 137 |
) |
| 138 |
|
| 139 |
|
| 140 |
class OAuthRedirect(MethodView): |
| 141 |
""" |
| 142 |
The OAuth2 redirect HTML for Swagger UI standard/implicit flow |
| 143 |
""" |
| 144 |
def get(self): |
| 145 |
return render_template( |
| 146 |
['flasgger/oauth2-redirect.html', 'flasgger/o2c.html'], |
| 147 |
) |
| 148 |
|
| 149 |
|
| 150 |
class APISpecsView(MethodView): |
| 151 |
""" |
| 152 |
The /apispec_1.json and other specs |
| 153 |
""" |
| 154 |
|
| 155 |
def __init__(self, *args, **kwargs): |
| 156 |
self.loader = kwargs.pop('loader') |
| 157 |
super(APISpecsView, self).__init__(*args, **kwargs) |
| 158 |
|
| 159 |
def get(self): |
| 160 |
""" |
| 161 |
The Swagger view get method outputs to /apispecs_1.json |
| 162 |
""" |
| 163 |
try: |
| 164 |
return jsonify(self.loader()) |
| 165 |
except: |
| 166 |
import logging |
| 167 |
logging.exception('jsonify failure; defaulting to json.dumps') |
| 168 |
specs = json.dumps(self.loader()) |
| 169 |
return Response(specs, mimetype='application/json') |
| 170 |
|
| 171 |
|
| 172 |
class SwaggerDefinition(object): |
| 173 |
""" |
| 174 |
Class based definition |
| 175 |
""" |
| 176 |
|
| 177 |
def __init__(self, name, obj, tags=None): |
| 178 |
self.name = name |
| 179 |
self.obj = obj |
| 180 |
self.tags = tags or [] |
| 181 |
|
| 182 |
|
| 183 |
class Swagger(object): |
| 184 |
|
| 185 |
DEFAULT_ENDPOINT = 'apispec_1' |
| 186 |
DEFAULT_CONFIG = { |
| 187 |
"headers": [ |
| 188 |
], |
| 189 |
"specs": [ |
| 190 |
{ |
| 191 |
"endpoint": DEFAULT_ENDPOINT, |
| 192 |
"route": '/{}.json'.format(DEFAULT_ENDPOINT), |
| 193 |
"rule_filter": lambda rule: True, |
| 194 |
"model_filter": lambda tag: True, |
| 195 |
} |
| 196 |
], |
| 197 |
"static_url_path": "/flasgger_static", |
| 198 |
|
| 199 |
"swagger_ui": True, |
| 200 |
"specs_route": "/apidocs/" |
| 201 |
} |
| 202 |
|
| 203 |
SCHEMA_TYPES = {'string': str, 'integer': int, 'number': float, |
| 204 |
'boolean': bool} |
| 205 |
SCHEMA_LOCATIONS = {'query': 'args', 'header': 'headers', |
| 206 |
'formData': 'form', 'body': 'json', 'path': 'path'} |
| 207 |
|
| 208 |
def _init_config(self, config, merge): |
| 209 |
""" Initializes self.config. If merge is set to true, then |
| 210 |
self.config will be set to with config + DEFAULT_CONFIG. |
| 211 |
""" |
| 212 |
if config and merge: |
| 213 |
self.config = dict(self.DEFAULT_CONFIG.copy(), **config) |
| 214 |
elif config and not merge: |
| 215 |
self.config = config |
| 216 |
elif not config: |
| 217 |
self.config = self.DEFAULT_CONFIG.copy() |
| 218 |
else: |
| 219 |
raise ValueError |
| 220 |
|
| 221 |
def __init__( |
| 222 |
self, app=None, config=None, sanitizer=None, template=None, |
| 223 |
template_file=None, decorators=None, validation_function=None, |
| 224 |
validation_error_handler=None, parse=False, format_checker=None, |
| 225 |
merge=False |
| 226 |
): |
| 227 |
self._configured = False |
| 228 |
self.endpoints = [] |
| 229 |
self.definition_models = [] |
| 230 |
self.sanitizer = sanitizer or BR_SANITIZER |
| 231 |
|
| 232 |
self._init_config(config, merge) |
| 233 |
|
| 234 |
self.template = template |
| 235 |
self.template_file = template_file |
| 236 |
self.decorators = decorators |
| 237 |
self.format_checker = format_checker or jsonschema.FormatChecker() |
| 238 |
|
| 239 |
def default_validation_function(data, schema): |
| 240 |
return jsonschema.validate( |
| 241 |
data, schema, format_checker=self.format_checker, |
| 242 |
) |
| 243 |
|
| 244 |
def default_error_handler(e, _, __): |
| 245 |
return abort(400, e.message) |
| 246 |
|
| 247 |
self.validation_function = validation_function\ |
| 248 |
or default_validation_function |
| 249 |
|
| 250 |
self.validation_error_handler = validation_error_handler\ |
| 251 |
or default_error_handler |
| 252 |
self.apispecs = {} |
| 253 |
self.parse = parse |
| 254 |
if app: |
| 255 |
self.init_app(app) |
| 256 |
|
| 257 |
def init_app(self, app, decorators=None): |
| 258 |
""" |
| 259 |
Initialize the app with Swagger plugin |
| 260 |
""" |
| 261 |
self.decorators = decorators or self.decorators |
| 262 |
self.app = app |
| 263 |
self.app.add_url_rule = swag_annotation(self.app.add_url_rule) |
| 264 |
|
| 265 |
self.load_config(app) |
| 266 |
|
| 267 |
if self.template_file is not None: |
| 268 |
self.template = self.load_swagger_file(self.template_file) |
| 269 |
self.register_views(app) |
| 270 |
self.add_headers(app) |
| 271 |
|
| 272 |
if self.parse: |
| 273 |
if RequestParser is None: |
| 274 |
raise RuntimeError('Please install flask_restful') |
| 275 |
self.parsers = {} |
| 276 |
self.schemas = {} |
| 277 |
self.parse_request(app) |
| 278 |
|
| 279 |
self._configured = True |
| 280 |
app.swag = self |
| 281 |
|
| 282 |
def load_swagger_file(self, filename): |
| 283 |
if not filename.startswith('/'): |
| 284 |
filename = os.path.join( |
| 285 |
self.app.root_path, |
| 286 |
filename |
| 287 |
) |
| 288 |
|
| 289 |
if filename.endswith('.json'): |
| 290 |
loader = json.load |
| 291 |
elif filename.endswith('.yml') or filename.endswith('.yaml'): |
| 292 |
def loader(stream): |
| 293 |
return yaml.safe_load(parse_imports(stream.read(), filename)) |
| 294 |
else: |
| 295 |
with codecs.open(filename, 'r', 'utf-8') as f: |
| 296 |
contents = f.read() |
| 297 |
contents = contents.strip() |
| 298 |
if contents[0] in ['{', '[']: |
| 299 |
loader = json.load |
| 300 |
else: |
| 301 |
def loader(stream): |
| 302 |
return yaml.safe_load( |
| 303 |
parse_imports(stream.read(), filename)) |
| 304 |
with codecs.open(filename, 'r', 'utf-8') as f: |
| 305 |
return loader(f) |
| 306 |
|
| 307 |
@property |
| 308 |
def configured(self): |
| 309 |
""" |
| 310 |
Return if `init_app` is configured |
| 311 |
""" |
| 312 |
return self._configured |
| 313 |
|
| 314 |
def get_url_mappings(self, rule_filter=None): |
| 315 |
""" |
| 316 |
Returns all werkzeug rules |
| 317 |
""" |
| 318 |
rule_filter = rule_filter or (lambda rule: True) |
| 319 |
app_rules = [ |
| 320 |
rule for rule in current_app.url_map.iter_rules() |
| 321 |
if rule_filter(rule) |
| 322 |
] |
| 323 |
return app_rules |
| 324 |
|
| 325 |
def get_def_models(self, definition_filter=None): |
| 326 |
""" |
| 327 |
Used for class based definitions |
| 328 |
""" |
| 329 |
model_filter = definition_filter or (lambda tag: True) |
| 330 |
return { |
| 331 |
definition.name: definition.obj |
| 332 |
for definition in self.definition_models |
| 333 |
if model_filter(definition) |
| 334 |
} |
| 335 |
|
| 336 |
def get_apispecs(self, endpoint='apispec_1'): |
| 337 |
if not self.app.debug and endpoint in self.apispecs: |
| 338 |
return self.apispecs[endpoint] |
| 339 |
|
| 340 |
spec = None |
| 341 |
for _spec in self.config['specs']: |
| 342 |
if _spec['endpoint'] == endpoint: |
| 343 |
spec = _spec |
| 344 |
break |
| 345 |
if not spec: |
| 346 |
raise RuntimeError( |
| 347 |
'Can`t find specs by endpoint {},' |
| 348 |
' check your flasger`s config'.format(endpoint)) |
| 349 |
|
| 350 |
data = { |
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
"info": self.config.get('info') or { |
| 356 |
"version": spec.get( |
| 357 |
'version', self.config.get('version', "0.0.1") |
| 358 |
), |
| 359 |
"title": spec.get( |
| 360 |
'title', self.config.get('title', "A swagger API") |
| 361 |
), |
| 362 |
"description": spec.get( |
| 363 |
'description', self.config.get('description', |
| 364 |
"powered by Flasgger") |
| 365 |
), |
| 366 |
"termsOfService": spec.get( |
| 367 |
'termsOfService', self.config.get('termsOfService', |
| 368 |
"/tos") |
| 369 |
), |
| 370 |
}, |
| 371 |
"paths": self.config.get('paths') or defaultdict(dict), |
| 372 |
"definitions": self.config.get('definitions') or defaultdict(dict) |
| 373 |
} |
| 374 |
|
| 375 |
openapi_version = self.config.get('openapi') |
| 376 |
|
| 377 |
|
| 378 |
if is_openapi3(openapi_version): |
| 379 |
data.setdefault('components', {})['schemas'] = data['definitions'] |
| 380 |
|
| 381 |
if openapi_version: |
| 382 |
data["openapi"] = openapi_version |
| 383 |
else: |
| 384 |
data["swagger"] = self.config.get('swagger') or self.config.get( |
| 385 |
'swagger_version', "2.0" |
| 386 |
) |
| 387 |
|
| 388 |
|
| 389 |
top_level_extension_options = get_vendor_extension_fields(self.config) |
| 390 |
if top_level_extension_options: |
| 391 |
data.update(top_level_extension_options) |
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
prefix_ids = self.config.get('prefix_ids') |
| 396 |
|
| 397 |
if self.config.get('host'): |
| 398 |
data['host'] = self.config.get('host') |
| 399 |
if self.config.get("basePath"): |
| 400 |
data["basePath"] = self.config.get('basePath') |
| 401 |
if self.config.get('schemes'): |
| 402 |
data['schemes'] = self.config.get('schemes') |
| 403 |
if self.config.get("securityDefinitions"): |
| 404 |
data["securityDefinitions"] = self.config.get( |
| 405 |
'securityDefinitions' |
| 406 |
) |
| 407 |
|
| 408 |
if is_openapi3(openapi_version): |
| 409 |
|
| 410 |
optional_oas3_fields = self.config.get( |
| 411 |
'optional_oas3_fields') or OPTIONAL_OAS3_FIELDS |
| 412 |
for key in optional_oas3_fields: |
| 413 |
if self.config.get(key): |
| 414 |
data[key] = self.config.get(key) |
| 415 |
|
| 416 |
|
| 417 |
if self.template is not None: |
| 418 |
data.update(self.template) |
| 419 |
|
| 420 |
paths = data['paths'] |
| 421 |
definitions = extract_schema(data) |
| 422 |
ignore_verbs = set( |
| 423 |
self.config.get('ignore_verbs', ("HEAD", "OPTIONS")) |
| 424 |
) |
| 425 |
|
| 426 |
|
| 427 |
optional_fields = self.config.get('optional_fields') or OPTIONAL_FIELDS |
| 428 |
|
| 429 |
for name, def_model in self.get_def_models( |
| 430 |
spec.get('definition_filter')).items(): |
| 431 |
description, swag = parse_definition_docstring( |
| 432 |
def_model, self.sanitizer) |
| 433 |
if name and swag: |
| 434 |
if description: |
| 435 |
swag.update({'description': description}) |
| 436 |
definitions[name].update(swag) |
| 437 |
|
| 438 |
specs = get_specs( |
| 439 |
self.get_url_mappings(spec.get('rule_filter')), ignore_verbs, |
| 440 |
optional_fields, self.sanitizer, |
| 441 |
openapi_version=openapi_version, |
| 442 |
doc_dir=self.config.get('doc_dir')) |
| 443 |
|
| 444 |
http_methods = ['get', 'post', 'put', 'delete'] |
| 445 |
for rule, verbs in specs: |
| 446 |
operations = dict() |
| 447 |
for verb, swag in verbs: |
| 448 |
|
| 449 |
if is_openapi3(openapi_version): |
| 450 |
update_dict = swag.get('components', {}).get('schemas', {}) |
| 451 |
else: |
| 452 |
update_dict = swag.get('definitions', {}) |
| 453 |
|
| 454 |
if type(update_dict) == list and type(update_dict[0]) == dict: |
| 455 |
|
| 456 |
update_dict, = update_dict |
| 457 |
definitions.update(update_dict) |
| 458 |
defs = [] |
| 459 |
defs += extract_definitions( |
| 460 |
defs, endpoint=rule.endpoint, verb=verb, |
| 461 |
prefix_ids=prefix_ids, |
| 462 |
openapi_version=openapi_version |
| 463 |
) |
| 464 |
|
| 465 |
params = swag.get('parameters', []) |
| 466 |
if verb in swag.keys(): |
| 467 |
verb_swag = swag.get(verb) |
| 468 |
if len(params) == 0 and verb.lower() in http_methods: |
| 469 |
params = verb_swag.get('parameters', []) |
| 470 |
|
| 471 |
defs += extract_definitions(params, |
| 472 |
endpoint=rule.endpoint, |
| 473 |
verb=verb, |
| 474 |
prefix_ids=prefix_ids, |
| 475 |
openapi_version=openapi_version) |
| 476 |
|
| 477 |
request_body = swag.get('requestBody') |
| 478 |
if request_body: |
| 479 |
content = request_body.get("content", {}) |
| 480 |
extract_definitions( |
| 481 |
list(content.values()), |
| 482 |
endpoint=rule.endpoint, |
| 483 |
verb=verb, |
| 484 |
prefix_ids=prefix_ids, |
| 485 |
openapi_version=openapi_version |
| 486 |
) |
| 487 |
|
| 488 |
callbacks = swag.get("callbacks", {}) |
| 489 |
if callbacks: |
| 490 |
callbacks = { |
| 491 |
str(key): value |
| 492 |
for key, value in callbacks.items() |
| 493 |
} |
| 494 |
extract_definitions( |
| 495 |
list(callbacks.values()), |
| 496 |
endpoint=rule.endpoint, |
| 497 |
verb=verb, |
| 498 |
prefix_ids=prefix_ids, |
| 499 |
openapi_version=openapi_version |
| 500 |
) |
| 501 |
|
| 502 |
responses = None |
| 503 |
if 'responses' in swag: |
| 504 |
responses = swag.get('responses', {}) |
| 505 |
responses = { |
| 506 |
str(key): value |
| 507 |
for key, value in responses.items() |
| 508 |
} |
| 509 |
if responses is not None: |
| 510 |
defs = defs + extract_definitions( |
| 511 |
responses.values(), |
| 512 |
endpoint=rule.endpoint, |
| 513 |
verb=verb, |
| 514 |
prefix_ids=prefix_ids, |
| 515 |
openapi_version=openapi_version |
| 516 |
) |
| 517 |
for definition in defs: |
| 518 |
if 'id' not in definition: |
| 519 |
definitions.update(definition) |
| 520 |
continue |
| 521 |
def_id = definition.pop('id') |
| 522 |
if def_id is not None: |
| 523 |
definitions[def_id].update(definition) |
| 524 |
|
| 525 |
operation = {} |
| 526 |
if swag.get('summary'): |
| 527 |
operation['summary'] = swag.get('summary') |
| 528 |
if swag.get('description'): |
| 529 |
operation['description'] = swag.get('description') |
| 530 |
if request_body: |
| 531 |
operation['requestBody'] = request_body |
| 532 |
if callbacks: |
| 533 |
operation['callbacks'] = callbacks |
| 534 |
if responses: |
| 535 |
operation['responses'] = responses |
| 536 |
|
| 537 |
if len(params) > 0: |
| 538 |
operation['parameters'] = params |
| 539 |
|
| 540 |
for key in optional_fields: |
| 541 |
if key in swag: |
| 542 |
value = swag.get(key) |
| 543 |
if key in ('produces', 'consumes'): |
| 544 |
if not isinstance(value, (list, tuple)): |
| 545 |
value = [value] |
| 546 |
|
| 547 |
operation[key] = value |
| 548 |
operations[verb] = operation |
| 549 |
|
| 550 |
if len(operations): |
| 551 |
try: |
| 552 |
|
| 553 |
prefix = self.template['swaggerUiPrefix'] |
| 554 |
except (KeyError, TypeError): |
| 555 |
prefix = '' |
| 556 |
srule = '{0}{1}'.format(prefix, rule) |
| 557 |
|
| 558 |
try: |
| 559 |
|
| 560 |
base_path = self.template['basePath'] |
| 561 |
|
| 562 |
if base_path: |
| 563 |
if base_path.endswith('/'): |
| 564 |
base_path = base_path[:-1] |
| 565 |
if base_path: |
| 566 |
|
| 567 |
|
| 568 |
if srule.startswith(base_path): |
| 569 |
srule = srule[len(base_path):] |
| 570 |
except (KeyError, TypeError): |
| 571 |
pass |
| 572 |
|
| 573 |
|
| 574 |
for arg in re.findall('(<([^<>]*:)?([^<>]*)>)', srule): |
| 575 |
srule = srule.replace(arg[0], '{%s}' % arg[2]) |
| 576 |
|
| 577 |
for key, val in operations.items(): |
| 578 |
if srule not in paths: |
| 579 |
paths[srule] = {} |
| 580 |
if key in paths[srule]: |
| 581 |
paths[srule][key].update(val) |
| 582 |
else: |
| 583 |
paths[srule][key] = val |
| 584 |
self.apispecs[endpoint] = data |
| 585 |
|
| 586 |
if is_openapi3(openapi_version): |
| 587 |
del data['definitions'] |
| 588 |
|
| 589 |
return data |
| 590 |
|
| 591 |
def definition(self, name, tags=None): |
| 592 |
""" |
| 593 |
Decorator to add class based definitions |
| 594 |
""" |
| 595 |
def wrapper(obj): |
| 596 |
self.definition_models.append(SwaggerDefinition(name, obj, |
| 597 |
tags=tags)) |
| 598 |
return obj |
| 599 |
return wrapper |
| 600 |
|
| 601 |
def load_config(self, app): |
| 602 |
""" |
| 603 |
Copy config from app |
| 604 |
""" |
| 605 |
self.config.update(app.config.get('SWAGGER', {})) |
| 606 |
|
| 607 |
def register_views(self, app): |
| 608 |
""" |
| 609 |
Register Flasgger views |
| 610 |
""" |
| 611 |
|
| 612 |
|
| 613 |
def wrap_view(view): |
| 614 |
if self.decorators: |
| 615 |
for decorator in self.decorators: |
| 616 |
view = decorator(view) |
| 617 |
return view |
| 618 |
|
| 619 |
if self.config.get('swagger_ui', True): |
| 620 |
uiversion = self.config.get('uiversion', 3) |
| 621 |
blueprint = Blueprint( |
| 622 |
self.config.get('endpoint', 'flasgger'), |
| 623 |
__name__, |
| 624 |
url_prefix=self.config.get('url_prefix', None), |
| 625 |
subdomain=self.config.get('subdomain', None), |
| 626 |
template_folder=self.config.get( |
| 627 |
'template_folder', 'ui{0}/templates'.format(uiversion) |
| 628 |
), |
| 629 |
static_folder=self.config.get( |
| 630 |
'static_folder', 'ui{0}/static'.format(uiversion) |
| 631 |
), |
| 632 |
static_url_path=self.config.get('static_url_path', None) |
| 633 |
) |
| 634 |
|
| 635 |
specs_route = self.config.get('specs_route', '/apidocs/') |
| 636 |
blueprint.add_url_rule( |
| 637 |
specs_route, |
| 638 |
'apidocs', |
| 639 |
view_func=wrap_view(APIDocsView().as_view( |
| 640 |
'apidocs', |
| 641 |
view_args=dict(config=self.config) |
| 642 |
)) |
| 643 |
) |
| 644 |
|
| 645 |
if uiversion < 3: |
| 646 |
redirect_default = specs_route + '/o2c.html' |
| 647 |
else: |
| 648 |
redirect_default = "/oauth2-redirect.html" |
| 649 |
|
| 650 |
blueprint.add_url_rule( |
| 651 |
self.config.get('oauth_redirect', redirect_default), |
| 652 |
'oauth_redirect', |
| 653 |
view_func=wrap_view(OAuthRedirect().as_view( |
| 654 |
'oauth_redirect' |
| 655 |
)) |
| 656 |
) |
| 657 |
|
| 658 |
|
| 659 |
blueprint.add_url_rule( |
| 660 |
'/apidocs/index.html', |
| 661 |
view_func=lambda: redirect(url_for('flasgger.apidocs')) |
| 662 |
) |
| 663 |
else: |
| 664 |
blueprint = Blueprint( |
| 665 |
self.config.get('endpoint', 'flasgger'), |
| 666 |
__name__ |
| 667 |
) |
| 668 |
|
| 669 |
for spec in self.config['specs']: |
| 670 |
self.endpoints.append(spec['endpoint']) |
| 671 |
blueprint.add_url_rule( |
| 672 |
spec['route'], |
| 673 |
spec['endpoint'], |
| 674 |
view_func=wrap_view(APISpecsView.as_view( |
| 675 |
spec['endpoint'], |
| 676 |
loader=partial( |
| 677 |
self.get_apispecs, endpoint=spec['endpoint']) |
| 678 |
)) |
| 679 |
) |
| 680 |
app.register_blueprint(blueprint) |
| 681 |
|
| 682 |
def add_headers(self, app): |
| 683 |
""" |
| 684 |
Inject headers after request |
| 685 |
""" |
| 686 |
@app.after_request |
| 687 |
def after_request(response): |
| 688 |
for header, value in self.config.get('headers'): |
| 689 |
response.headers[header] = value |
| 690 |
return response |
| 691 |
|
| 692 |
def parse_request(self, app): |
| 693 |
@app.before_request |
| 694 |
def before_request(): |
| 695 |
""" |
| 696 |
Parse and validate request data(query, form, header and body), |
| 697 |
set data to `request.parsed_data` |
| 698 |
""" |
| 699 |
|
| 700 |
subs = [] |
| 701 |
for sub in str(request.url_rule).split('/'): |
| 702 |
if '<' in sub: |
| 703 |
if ':' in sub: |
| 704 |
start = sub.index(':') + 1 |
| 705 |
else: |
| 706 |
start = 1 |
| 707 |
subs.append('{{{:s}}}'.format(sub[start:-1])) |
| 708 |
else: |
| 709 |
subs.append(sub) |
| 710 |
path = '/'.join(subs) |
| 711 |
path_key = path + request.method.lower() |
| 712 |
|
| 713 |
if not self.app.debug and path_key in self.parsers: |
| 714 |
parsers = self.parsers[path_key] |
| 715 |
schemas = self.schemas[path_key] |
| 716 |
else: |
| 717 |
doc = None |
| 718 |
definitions = None |
| 719 |
for spec in self.config['specs']: |
| 720 |
apispec = self.get_apispecs(endpoint=spec['endpoint']) |
| 721 |
if path in apispec['paths']: |
| 722 |
if request.method.lower() in apispec['paths'][path]: |
| 723 |
doc = apispec['paths'][path][ |
| 724 |
request.method.lower()] |
| 725 |
definitions = extract_schema(apispec) |
| 726 |
break |
| 727 |
if not doc: |
| 728 |
return |
| 729 |
|
| 730 |
parsers = defaultdict(RequestParser) |
| 731 |
schemas = defaultdict( |
| 732 |
lambda: {'type': 'object', 'properties': defaultdict(dict)} |
| 733 |
) |
| 734 |
self.update_schemas_parsers(doc, schemas, parsers, definitions) |
| 735 |
self.schemas[path_key] = schemas |
| 736 |
self.parsers[path_key] = parsers |
| 737 |
|
| 738 |
parsed_data = {'path': request.view_args} |
| 739 |
for location in parsers.keys(): |
| 740 |
parsed_data[location] = parsers[location].parse_args() |
| 741 |
if 'json' in schemas: |
| 742 |
parsed_data['json'] = request.json or {} |
| 743 |
for location, data in parsed_data.items(): |
| 744 |
try: |
| 745 |
ret = self.validation_function(data, schemas[location]) |
| 746 |
print(ret) |
| 747 |
except jsonschema.ValidationError as e: |
| 748 |
self.validation_error_handler(e, data, schemas[location]) |
| 749 |
|
| 750 |
setattr(request, 'parsed_data', parsed_data) |
| 751 |
|
| 752 |
def update_schemas_parsers(self, doc, schemas, parsers, definitions): |
| 753 |
''' |
| 754 |
Schemas and parsers would be updated here from doc |
| 755 |
''' |
| 756 |
if self.is_openapi3(): |
| 757 |
|
| 758 |
location = 'json' |
| 759 |
json_schema = None |
| 760 |
|
| 761 |
|
| 762 |
for name, value in doc.get('requestBody', {}).get('content', {})\ |
| 763 |
.items(): |
| 764 |
if 'application/json' in name: |
| 765 |
|
| 766 |
json_schema = value.get('schema', {}) |
| 767 |
else: |
| 768 |
|
| 769 |
parsers[location].add_argument( |
| 770 |
name, |
| 771 |
type=self.SCHEMA_TYPES[ |
| 772 |
value['schema'].get('type', None) |
| 773 |
if 'schema' in value |
| 774 |
else value.get('type', None)], |
| 775 |
required=value.get('required', False), |
| 776 |
|
| 777 |
|
| 778 |
location=self.SCHEMA_LOCATIONS['body'], |
| 779 |
store_missing=False |
| 780 |
) |
| 781 |
|
| 782 |
|
| 783 |
if (json_schema is not None) and type(json_schema) == dict: |
| 784 |
|
| 785 |
schemas[location] = json_schema |
| 786 |
self.set_schemas(schemas, location, definitions) |
| 787 |
|
| 788 |
else: |
| 789 |
for param in doc.get('parameters', []): |
| 790 |
location = self.SCHEMA_LOCATIONS[param['in']] |
| 791 |
if location == 'json': |
| 792 |
schemas[location] = param['schema'] |
| 793 |
self.set_schemas(schemas, location, definitions) |
| 794 |
else: |
| 795 |
name = param['name'] |
| 796 |
if location != 'path': |
| 797 |
parsers[location].add_argument( |
| 798 |
name, |
| 799 |
type=self.SCHEMA_TYPES[ |
| 800 |
param['schema'].get('type', None) |
| 801 |
if 'schema' in param |
| 802 |
else param.get('type', None)], |
| 803 |
required=param.get('required', False), |
| 804 |
location=self.SCHEMA_LOCATIONS[ |
| 805 |
param['in']], |
| 806 |
store_missing=False) |
| 807 |
|
| 808 |
for k in param: |
| 809 |
if k != 'required': |
| 810 |
schemas[ |
| 811 |
location]['properties'][name][k] = param[k] |
| 812 |
|
| 813 |
def set_schemas(self, schemas: dict, location: str, |
| 814 |
definitions: dict): |
| 815 |
if is_openapi3(self.config.get('openapi')): |
| 816 |
schemas[location]['components'] = {'schemas': dict(definitions)} |
| 817 |
else: |
| 818 |
schemas[location]['definitions'] = dict(definitions) |
| 819 |
|
| 820 |
def validate( |
| 821 |
self, schema_id, validation_function=None, |
| 822 |
validation_error_handler=None): |
| 823 |
""" |
| 824 |
A decorator that is used to validate incoming requests data |
| 825 |
against a schema |
| 826 |
|
| 827 |
swagger = Swagger(app) |
| 828 |
|
| 829 |
@app.route('/pets', methods=['POST']) |
| 830 |
@swagger.validate('Pet') |
| 831 |
@swag_from("pet_post_endpoint.yml") |
| 832 |
def post(): |
| 833 |
return db.insert(request.data) |
| 834 |
|
| 835 |
This annotation only works if the endpoint is already swagged, |
| 836 |
i.e. placing @swag_from above @validate or not declaring the |
| 837 |
swagger specifications in the method's docstring *won't work* |
| 838 |
|
| 839 |
Naturally, if you use @app.route annotation it still needs to |
| 840 |
be the outermost annotation |
| 841 |
|
| 842 |
:param schema_id: the id of the schema with which the data will |
| 843 |
be validated |
| 844 |
|
| 845 |
:param validation_function: custom validation function which |
| 846 |
takes the positional arguments: data to be validated at |
| 847 |
first and schema to validate against at second |
| 848 |
|
| 849 |
:param validation_error_handler: custom function to handle |
| 850 |
exceptions thrown when validating which takes the exception |
| 851 |
thrown as the first, the data being validated as the second |
| 852 |
and the schema being used to validate as the third argument |
| 853 |
""" |
| 854 |
|
| 855 |
if validation_function is None: |
| 856 |
validation_function = self.validation_function |
| 857 |
|
| 858 |
if validation_error_handler is None: |
| 859 |
validation_error_handler = self.validation_error_handler |
| 860 |
|
| 861 |
def decorator(func): |
| 862 |
@wraps(func) |
| 863 |
def wrapper(*args, **kwargs): |
| 864 |
specs = get_schema_specs(schema_id, self) |
| 865 |
validate( |
| 866 |
schema_id=schema_id, specs=specs, |
| 867 |
validation_function=validation_function, |
| 868 |
validation_error_handler=validation_error_handler, |
| 869 |
openapi_version=self.config.get('openapi') |
| 870 |
) |
| 871 |
return func(*args, **kwargs) |
| 872 |
|
| 873 |
return wrapper |
| 874 |
|
| 875 |
return decorator |
| 876 |
|
| 877 |
def get_schema(self, schema_id): |
| 878 |
""" |
| 879 |
This method finds a schema known to Flasgger and returns it. |
| 880 |
|
| 881 |
:raise KeyError: when the specified :param schema_id: is not |
| 882 |
found by Flasgger |
| 883 |
|
| 884 |
:param schema_id: the id of the desired schema |
| 885 |
""" |
| 886 |
schema_specs = get_schema_specs(schema_id, self) |
| 887 |
|
| 888 |
if schema_specs is None: |
| 889 |
raise KeyError( |
| 890 |
'Specified schema_id \'{0}\' not found'.format(schema_id)) |
| 891 |
|
| 892 |
for schema in ( |
| 893 |
parameter.get('schema') for parameter in |
| 894 |
schema_specs['parameters']): |
| 895 |
if schema is not None and schema.get('id').lower() == schema_id: |
| 896 |
return schema |
| 897 |
|
| 898 |
def is_openapi3(self): |
| 899 |
return is_openapi3(self.config.get('openapi')) |
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
Flasgger = Swagger |
| 904 |
|
| 905 |
|
| 906 |
class LazyJSONEncoder(DefaultJSONProvider): |
| 907 |
def default(self, obj): |
| 908 |
if isinstance(obj, LazyString): |
| 909 |
return str(obj) |
| 910 |
return super(LazyJSONEncoder, self).default(obj) |