Tornado OpenAPI 3 request and response validation library
Project description
Tornado OpenAPI 3 request and response validation library.
Provides integration between the Tornado web framework and Openapi-core library for validating request and response objects against an OpenAPI 3 specification.
Adding validation to request handlers
from openapi_core import create_spec # type: ignore
from openapi_core.exceptions import OpenAPIError # type: ignore
from openapi_core.deserializing.exceptions import DeserializeError # type: ignore
from openapi_core.schema.media_types.exceptions import ( # type: ignore
InvalidContentType,
)
from openapi_core.unmarshalling.schemas.exceptions import ValidateError # type: ignore
from tornado.web import RequestHandler
from tornado_openapi3 import RequestValidator
import yaml
class OpenAPIRequestHandler(RequestHandler):
async def prepare(self) -> None:
maybe_coro = super().prepare()
if maybe_coro and asyncio.iscoroutine(maybe_coro): # pragma: no cover
await maybe_coro
spec = create_spec(yaml.safe_load(self.render_string("openapi.yaml")))
validator = RequestValidator(spec)
result = validator.validate(self.request)
try:
result.raise_for_errors()
except InvalidContentType:
self.set_status(415)
self.finish()
except (DeserializeError, ValidateError) as e:
self.set_status(400)
self.finish()
except OpenAPIError:
raise
Validating a response
from tornado.testing import AsyncHTTPTestCase
from tornado_openapi3 import ResponseValidator
from myapplication import create_app, spec
class TestResponses(AsyncHTTPTestCase):
def get_app(self) -> Application:
return create_app()
def test_status(self) -> None:
validator = ResponseValidator(spec)
response = self.fetch("/status")
result = validator.validate(response)
result.raise_for_errors()
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
tornado-openapi3-0.2.1.tar.gz
(4.2 kB
view hashes)
Built Distribution
Close
Hashes for tornado_openapi3-0.2.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3b5590bf47fc9419df74383b7fcd96e1d04f4ac34a1f198eb47af61f01f99a84 |
|
MD5 | 252619148bbba1e68f0fcb95944b7b8b |
|
BLAKE2b-256 | 7ba020a8aec5cbcdee7f5497a89fda0e618e115ab126ed6474f7709cf012a43e |