Falcon compat module

This commit is contained in:
p1c2u 2021-05-01 00:30:55 +01:00
parent ffa54aae88
commit 2c864595e5
4 changed files with 31 additions and 15 deletions

View file

@ -0,0 +1,24 @@
"""OpenAPI core contrib falcon compat module"""
try:
from falcon import App # noqa: F401
HAS_FALCON3 = True
except ImportError:
HAS_FALCON3 = False
def get_request_media(req, default=None):
# in falcon 3 media is deprecated
return req.get_media(default_when_empty=default) if HAS_FALCON3 else \
(req.media if req.media else default)
def get_response_text(resp):
# in falcon 3 body is deprecated
return getattr(resp, 'text') if HAS_FALCON3 else \
getattr(resp, 'body')
def set_response_text(resp, text):
# in falcon 3 body is deprecated
setattr(resp, 'text', text) if HAS_FALCON3 else \
setattr(resp, 'body', text)

View file

@ -5,6 +5,8 @@ from falcon.constants import MEDIA_JSON
from falcon.status_codes import (
HTTP_400, HTTP_404, HTTP_405, HTTP_415,
)
from openapi_core.contrib.falcon.compat import set_response_text
from openapi_core.templating.media_types.exceptions import MediaTypeNotFound
from openapi_core.templating.paths.exceptions import (
ServerNotFound, OperationNotFound, PathNotFound,
@ -41,11 +43,7 @@ class FalconOpenAPIErrorsHandler(object):
resp.content_type = MEDIA_JSON
resp.status = cls.FALCON_STATUS_CODES.get(
data_error_max['status'], HTTP_400)
# in falcon 3 body is deprecated
if hasattr(resp, 'text'):
resp.text = data_str
else:
resp.body = data_str
set_response_text(resp, data_str)
resp.complete = True
@classmethod

View file

@ -3,6 +3,7 @@ from json import dumps
from werkzeug.datastructures import ImmutableMultiDict
from openapi_core.contrib.falcon.compat import get_request_media
from openapi_core.validation.request.datatypes import (
OpenAPIRequest, RequestParameters,
)
@ -21,11 +22,7 @@ class FalconOpenAPIRequestFactory:
# gets deduced by path finder against spec
path = {}
# in falcon 3 we must hadle empty media or an exception will be raised
if hasattr(request, "get_media"):
media = request.get_media(default_when_empty=default)
else:
media = request.media if request.media else default
media = get_request_media(request, default=default)
# Support falcon-jsonify.
body = (
dumps(getattr(request, "json", media))

View file

@ -1,4 +1,5 @@
"""OpenAPI core contrib falcon responses module"""
from openapi_core.contrib.falcon.compat import get_response_text
from openapi_core.validation.response.datatypes import OpenAPIResponse
@ -13,11 +14,7 @@ class FalconOpenAPIResponseFactory(object):
else:
mimetype = response.options.default_media_type
# in falcon 3 body is deprecated
if hasattr(response, "text"):
data = response.text
else:
data = response.body
data = get_response_text(response)
return OpenAPIResponse(
data=data,