tornado-openapi3/tornado_openapi3/requests.py

58 lines
2.1 KiB
Python
Raw Normal View History

2020-09-17 03:04:11 +00:00
import itertools
from urllib.parse import parse_qsl
from typing import Union
2020-09-17 03:04:11 +00:00
from openapi_core.validation.request.datatypes import ( # type: ignore
RequestParameters,
OpenAPIRequest,
)
from openapi_core.validation.request import validators # type: ignore
from tornado.httpclient import HTTPRequest # type: ignore
from tornado.httputil import HTTPServerRequest # type: ignore
2020-09-17 03:04:11 +00:00
from werkzeug.datastructures import ImmutableMultiDict, Headers
class TornadoRequestFactory:
@classmethod
def create(cls, request: Union[HTTPRequest, HTTPServerRequest]) -> OpenAPIRequest:
if isinstance(request, HTTPRequest):
if request.url:
path, _, querystring = request.url.partition("?")
query_arguments: ImmutableMultiDict[str, str] = ImmutableMultiDict(
parse_qsl(querystring)
)
else:
path = ""
query_arguments = ImmutableMultiDict()
2020-09-17 03:04:11 +00:00
else:
path, _, _ = request.full_url().partition("?")
2020-12-04 18:37:25 +00:00
if path == "://":
path = ""
query_arguments = ImmutableMultiDict(
itertools.chain(
*[
[(k, v.decode("utf-8")) for v in vs]
for k, vs in request.query_arguments.items()
]
)
2020-09-17 03:04:11 +00:00
)
return OpenAPIRequest(
full_url_pattern=path,
method=request.method.lower() if request.method else "get",
parameters=RequestParameters(
2020-09-18 03:39:35 +00:00
query=query_arguments, header=Headers(request.headers.get_all())
2020-09-17 03:04:11 +00:00
),
body=request.body.decode("utf-8") if request.body else "",
2020-11-20 00:37:58 +00:00
mimetype=request.headers.get(
"Content-Type", "application/x-www-form-urlencoded"
),
2020-09-17 03:04:11 +00:00
)
class RequestValidator(validators.RequestValidator):
def validate(self, request: Union[HTTPRequest, HTTPServerRequest]):
return super().validate(TornadoRequestFactory.create(request))
__all__ = ["RequestValidator", "TornadoRequestFactory"]