openapi-core/openapi_core/shortcuts.py

72 lines
2.1 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 import default_handlers
2018-04-18 10:39:03 +00:00
from openapi_core.schema.media_types.exceptions import OpenAPIMediaTypeError
from openapi_core.schema.parameters.exceptions import OpenAPIParameterError
from openapi_core.schema.request_bodies.exceptions import (
OpenAPIRequestBodyError,
)
from openapi_core.schema.schemas.exceptions import OpenAPISchemaError
2018-04-17 12:18:40 +00:00
from openapi_core.schema.specs.factories import SpecFactory
2018-04-17 12:38:23 +00:00
from openapi_core.validation.request.validators import RequestValidator
from openapi_core.validation.response.validators import ResponseValidator
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)
2019-09-03 00:38:19 +00:00
spec_factory = SpecFactory(spec_resolver)
2017-09-21 11:51:37 +00:00
return spec_factory.create(spec_dict, spec_url=spec_url)
2017-11-03 11:40:05 +00:00
2018-03-02 09:16:49 +00:00
def validate_parameters(spec, request, wrapper_class=None):
if wrapper_class is not None:
2017-11-03 15:04:18 +00:00
request = wrapper_class(request)
2017-11-03 11:40:05 +00:00
validator = RequestValidator(spec)
result = validator.validate(request)
2018-03-02 09:16:49 +00:00
2017-11-03 11:40:05 +00:00
try:
2017-11-03 14:55:21 +00:00
result.raise_for_errors()
2018-04-18 10:39:03 +00:00
except (
OpenAPIRequestBodyError, OpenAPIMediaTypeError,
OpenAPISchemaError,
):
2017-11-03 11:40:05 +00:00
return result.parameters
else:
return result.parameters
2018-03-02 09:16:49 +00:00
def validate_body(spec, request, wrapper_class=None):
if wrapper_class is not None:
2017-11-03 15:04:18 +00:00
request = wrapper_class(request)
2017-11-03 11:40:05 +00:00
validator = RequestValidator(spec)
result = validator.validate(request)
2018-03-02 09:16:49 +00:00
2017-11-03 11:40:05 +00:00
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,
2018-03-02 09:16:49 +00:00
request_wrapper_class=None,
response_wrapper_class=None):
if request_wrapper_class is not None:
2017-11-06 14:32:46 +00:00
request = request_wrapper_class(request)
2018-03-02 09:16:49 +00:00
if response_wrapper_class is not None:
2017-11-06 14:32:46 +00:00
response = response_wrapper_class(response)
validator = ResponseValidator(spec)
result = validator.validate(request, response)
result.raise_for_errors()
return result.data