openapi-core/openapi_core/shortcuts.py

63 lines
1.9 KiB
Python
Raw Normal View History

2017-09-21 11:51:37 +00:00
"""OpenAPI core shortcuts module"""
from jsonschema.validators import RefResolver
from openapi_spec_validator.validators import Dereferencer
from openapi_spec_validator import default_handlers
2017-11-03 11:40:05 +00:00
from openapi_core.exceptions import OpenAPIParameterError, OpenAPIBodyError
2017-09-21 11:51:37 +00:00
from openapi_core.specs import SpecFactory
2017-11-06 14:32:46 +00:00
from openapi_core.validators import RequestValidator, ResponseValidator
from openapi_core.wrappers import FlaskOpenAPIRequest, FlaskOpenAPIResponse
2017-09-21 11:51:37 +00:00
def create_spec(spec_dict, spec_url=''):
spec_resolver = RefResolver(
spec_url, spec_dict, handlers=default_handlers)
dereferencer = Dereferencer(spec_resolver)
spec_factory = SpecFactory(dereferencer)
return spec_factory.create(spec_dict, spec_url=spec_url)
2017-11-03 11:40:05 +00:00
2017-11-03 15:04:18 +00:00
def validate_parameters(spec, request, wrapper_class=FlaskOpenAPIRequest):
if wrapper_class:
request = wrapper_class(request)
2017-11-03 11:40:05 +00:00
validator = RequestValidator(spec)
result = validator.validate(request)
try:
2017-11-03 14:55:21 +00:00
result.raise_for_errors()
2017-11-03 11:40:05 +00:00
except OpenAPIBodyError:
return result.parameters
else:
return result.parameters
2017-11-03 15:04:18 +00:00
def validate_body(spec, request, wrapper_class=FlaskOpenAPIRequest):
if wrapper_class:
request = wrapper_class(request)
2017-11-03 11:40:05 +00:00
validator = RequestValidator(spec)
result = validator.validate(request)
try:
2017-11-03 14:55:21 +00:00
result.raise_for_errors()
2017-11-03 11:40:05 +00:00
except OpenAPIParameterError:
return result.body
else:
return result.body
2017-11-06 14:32:46 +00:00
def validate_data(
spec, request, response,
request_wrapper_class=FlaskOpenAPIRequest,
response_wrapper_class=FlaskOpenAPIResponse):
if request_wrapper_class:
request = request_wrapper_class(request)
if response_wrapper_class:
response = response_wrapper_class(response)
validator = ResponseValidator(spec)
result = validator.validate(request, response)
result.raise_for_errors()
return result.data