tornado-openapi3/tornado_openapi3/requests.py

59 lines
1.8 KiB
Python
Raw Permalink Normal View History

2024-10-18 21:04:45 +00:00
import typing
import urllib.parse
from urllib.parse import parse_qsl
2020-09-17 03:04:11 +00:00
2024-10-18 21:04:45 +00:00
from openapi_core.validation.request.datatypes import RequestParameters
from tornado.httpclient import HTTPRequest
from tornado.httputil import HTTPServerRequest, parse_cookie
2020-09-17 03:04:11 +00:00
from werkzeug.datastructures import ImmutableMultiDict, Headers
2024-10-18 21:04:45 +00:00
class TornadoOpenAPIRequest:
def __init__(self, request: typing.Union[HTTPRequest, HTTPServerRequest]) -> None:
"""Create an OpenAPI request from Tornado request objects.
2021-02-26 17:03:04 +00:00
Supports both :class:`tornado.httpclient.HTTPRequest` and
:class:`tornado.httputil.HTTPServerRequest` objects.
"""
2024-10-18 21:04:45 +00:00
self.request = request
if isinstance(request, HTTPRequest):
2024-10-18 21:04:45 +00:00
parts = urllib.parse.urlparse(request.url)
2020-09-17 03:04:11 +00:00
else:
2024-10-18 21:04:45 +00:00
parts = urllib.parse.urlparse(request.full_url())
protocol = parts.scheme
host = parts.netloc
path = parts.path
query_arguments = parse_qsl(parts.query)
self.protocol = protocol
self.host = host
self.path = path
cookies = {}
for values in request.headers.get_list("Cookie"):
cookies.update(parse_cookie(values))
self.parameters = RequestParameters(
query=ImmutableMultiDict(query_arguments),
header=Headers(request.headers.get_all()),
cookie=ImmutableMultiDict(cookies),
)
self.content_type = request.headers.get(
"Content-Type", "application/x-www-form-urlencoded"
2020-09-17 03:04:11 +00:00
)
2024-10-18 21:04:45 +00:00
@property
def host_url(self) -> str:
return "{}://{}".format(self.protocol, self.host)
2024-10-18 21:04:45 +00:00
@property
def method(self) -> str:
method = self.request.method or "GET"
return method.lower()
2021-02-26 20:34:54 +00:00
2024-10-18 21:04:45 +00:00
@property
def body(self) -> typing.Optional[bytes]:
return self.request.body
2024-10-18 21:04:45 +00:00
__all__ = ["TornadoOpenAPIRequest"]