2020-03-02 16:05:36 +00:00
|
|
|
"""OpenAPI core contrib requests requests module"""
|
2021-03-24 13:06:35 +00:00
|
|
|
from __future__ import absolute_import
|
2020-03-02 16:05:36 +00:00
|
|
|
from werkzeug.datastructures import ImmutableMultiDict
|
2021-03-24 13:06:35 +00:00
|
|
|
from requests import Request
|
|
|
|
from six.moves.urllib.parse import urlparse, parse_qs
|
2020-03-02 16:05:36 +00:00
|
|
|
|
|
|
|
from openapi_core.validation.request.datatypes import (
|
|
|
|
RequestParameters, OpenAPIRequest,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class RequestsOpenAPIRequestFactory(object):
|
|
|
|
|
|
|
|
@classmethod
|
2021-03-24 13:06:35 +00:00
|
|
|
def create(cls, request):
|
2020-11-17 08:12:56 +00:00
|
|
|
"""
|
|
|
|
Converts a requests request to an OpenAPI one
|
|
|
|
|
|
|
|
Internally converts to a `PreparedRequest` first to parse the exact
|
|
|
|
payload being sent
|
|
|
|
"""
|
|
|
|
if isinstance(request, Request):
|
|
|
|
request = request.prepare()
|
|
|
|
|
|
|
|
# Method
|
2020-03-02 16:05:36 +00:00
|
|
|
method = request.method.lower()
|
|
|
|
|
2020-11-17 08:12:56 +00:00
|
|
|
# Cookies
|
2021-03-24 12:56:55 +00:00
|
|
|
cookie = {}
|
2020-11-17 08:12:56 +00:00
|
|
|
if request._cookies is not None:
|
|
|
|
# cookies are stored in a cookiejar object
|
|
|
|
cookie = request._cookies.get_dict()
|
|
|
|
|
|
|
|
# Preparing a request formats the URL with params, strip them out again
|
|
|
|
o = urlparse(request.url)
|
|
|
|
params = parse_qs(o.query)
|
|
|
|
# extract the URL without query parameters
|
|
|
|
url = o._replace(query=None).geturl()
|
2020-03-02 16:05:36 +00:00
|
|
|
|
|
|
|
# gets deduced by path finder against spec
|
|
|
|
path = {}
|
|
|
|
|
2021-03-24 13:06:35 +00:00
|
|
|
# Order matters because all python requests issued from a session
|
|
|
|
# include Accept */* which does not necessarily match the content type
|
2020-11-17 08:12:56 +00:00
|
|
|
mimetype = request.headers.get('Content-Type') or \
|
|
|
|
request.headers.get('Accept')
|
|
|
|
|
2021-03-24 13:06:35 +00:00
|
|
|
# Headers - request.headers is not an instance of dict
|
|
|
|
# which is expected
|
2020-11-17 08:12:56 +00:00
|
|
|
header = dict(request.headers)
|
|
|
|
|
|
|
|
# Body
|
|
|
|
# TODO: figure out if request._body_position is relevant
|
|
|
|
body = request.body
|
|
|
|
|
2020-03-02 16:05:36 +00:00
|
|
|
parameters = RequestParameters(
|
2020-11-17 08:12:56 +00:00
|
|
|
query=ImmutableMultiDict(params),
|
|
|
|
header=header,
|
2020-03-02 16:05:36 +00:00
|
|
|
cookie=cookie,
|
|
|
|
path=path,
|
|
|
|
)
|
|
|
|
return OpenAPIRequest(
|
2020-11-17 08:12:56 +00:00
|
|
|
full_url_pattern=url,
|
2020-03-02 16:05:36 +00:00
|
|
|
method=method,
|
|
|
|
parameters=parameters,
|
2020-11-17 08:12:56 +00:00
|
|
|
body=body,
|
2020-03-02 16:05:36 +00:00
|
|
|
mimetype=mimetype,
|
|
|
|
)
|