コード例 #1
0
def test_unhandled_exception(app):
    from falcon import __version__ as falcon_version

    # Falcon v3 and above will not raise an uncaught exception
    if int(falcon_version.split('.', 1)[0]) >= 3:
        app.put('/bad_response', status=500, expect_errors=True)
    else:
        with pytest.raises(app.BadPutRequest):
            app.put('/bad_response')
コード例 #2
0
ファイル: falcon.py プロジェクト: ciwei100000/mozjs-debian
    def setup_once():
        # type: () -> None
        try:
            version = tuple(map(int, FALCON_VERSION.split(".")))
        except (ValueError, TypeError):
            raise DidNotEnable("Unparseable Falcon version: {}".format(FALCON_VERSION))

        if version < (1, 4):
            raise DidNotEnable("Falcon 1.4 or newer required.")

        _patch_wsgi_app()
        _patch_handle_exception()
        _patch_prepare_middleware()
コード例 #3
0
def setup_falcon_error_handlers(api: "falcon.API"):  # pragma: no cover
    """
    Setups the error handler for `APIException`.

    :param api: falcon.API
    :return:
    """
    # try to use a faster json library
    try:
        import ujson as json
    except ImportError:
        import json

    from falcon import HTTP_400, HTTP_500, Response, Request, __version__

    major_version = int(__version__.split(".", maxsplit=1)[0])

    # Falcon 2.0.0 changed the order of the arguments
    if major_version >= 2:

        def handle_api_exception(
            _rq: Request, _rp: Response, exc: "APIException", _p: dict
        ):
            """
            Handles APIExceptions in Falcon.
            """
            code = HTTP_400 if exc.status_code == 400 else HTTP_500
            detail = (
                {"error": exc.detail} if isinstance(exc.detail, str) else exc.detail
            )
            _rp.body = json.dumps(detail)
            _rp.status = code

    else:

        def handle_api_exception(exc: "APIException", _rq, _rp: Response, _p):
            """
            Handles APIExceptions in Falcon.
            """
            code = HTTP_400 if exc.status_code == 400 else HTTP_500
            detail = (
                {"error": exc.detail} if isinstance(exc.detail, str) else exc.detail
            )
            _rp.body = json.dumps(detail)
            _rp.status = code

    api.add_error_handler(APIException, handler=handle_api_exception)
コード例 #4
0
from falcon_caching.options import CacheEvictionStrategy, HttpMethods
import logging
import re
import msgpack
from typing import TYPE_CHECKING, Any, Dict, Tuple

if TYPE_CHECKING:
    from falcon_caching.cache import Cache

logger = logging.getLogger(__name__)

_DECORABLE_METHOD_NAME = re.compile(r'^on_({})(_\w+)?$'.format('|'.join(
    method.lower() for method in COMBINED_METHODS)))

# what is the Falcon main version (eg 2 or 3, etc)
FALCONVERSION_MAIN = int(FALCONVERSION.split('.')[0])


class Middleware:
    """ It integrates a cache object with Falcon by turning it into
    a Falcon Middleware
    """
    def __init__(self, cache: 'Cache', config: Dict[str, Any]) -> None:
        self.cache = cache
        self.cache_config = config

    def process_resource(self, req, resp, resource, params):
        """ Determine if the given request is marked for caching and if yes,
        then look it up in the cache and if found, then return the cached value
        """