Python sanic.exceptions.NotFound() Examples

The following are 19 code examples of sanic.exceptions.NotFound(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sanic.exceptions , or try the search function .
Example #1
Source File: test_middleware.py    From sanic with MIT License 6 votes vote down vote up
def test_middleware_response_exception(app):
    result = {"status_code": None}

    @app.middleware("response")
    async def process_response(request, response):
        result["status_code"] = response.status
        return response

    @app.exception(NotFound)
    async def error_handler(request, exception):
        return text("OK", exception.status_code)

    @app.route("/")
    async def handler(request):
        return text("FAIL")

    request, response = app.test_client.get("/page_not_found")
    assert response.text == "OK"
    assert result["status_code"] == 404 
Example #2
Source File: test_plugin_middleware.py    From sanicpluginsframework with MIT License 6 votes vote down vote up
def test_middleware_response_exception(spf):
    app = spf._app
    plugin = TestPlugin()
    result = {'status_code': None}

    @plugin.middleware('response')
    async def process_response(reqest, response):
        result['status_code'] = response.status
        return response

    @plugin.exception(NotFound)
    async def error_handler(request, exception):
        return text('OK', exception.status_code)

    @plugin.route('/')
    async def handler(request):
        return text('FAIL')

    spf.register_plugin(plugin)
    request, response = app.test_client.get('/page_not_found')
    assert response.text == 'OK'
    assert result['status_code'] == 404 
Example #3
Source File: user.py    From pubgate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def token_get(request):
    user = await User.find_one(dict(
        name=request.json["username"].lower().lstrip('@')
    ))
    if not user:
        raise exceptions.NotFound("User not found")

    if not check_password_hash(user.password, request.json["password"]):
        return response.json({"error": "password incorrect"}, status=401)

    token = getattr(user, "token")
    if not token:
        token = random_object_id()
        #TODO make token expire
        await User.update_one({'name': request.json["username"]},
                              {'$set': {'token': token}})

    return response.json({'access_token': token}) 
Example #4
Source File: router.py    From sanic with MIT License 6 votes vote down vote up
def get(self, request):
        """Get a request handler based on the URL of the request, or raises an
        error

        :param request: Request object
        :return: handler, arguments, keyword arguments
        """
        # No virtual hosts specified; default behavior
        if not self.hosts:
            return self._get(request.path, request.method, "")
        # virtual hosts specified; try to match route to the host header

        try:
            return self._get(
                request.path, request.method, request.headers.get("Host", "")
            )
        # try default hosts
        except NotFound:
            return self._get(request.path, request.method, "") 
Example #5
Source File: test_exception_interception.py    From sanic-cors with MIT License 5 votes vote down vote up
def add_routes(app):
    #@app.route('/test_no_acl_abort_404')
    #@app.route('/test_acl_abort_404')
    def test_acl_abort_404(request):
        raise NotFound("")
    app.route('/test_no_acl_abort_404')(test_acl_abort_404)
    app.route('/test_acl_abort_404')(test_acl_abort_404)

    #@app.route('/test_no_acl_async_abort_404')
    #@app.route('/test_acl_async_abort_404')
    async def test_acl_async_abort_404(request):
        raise NotFound("")
    app.route('/test_no_acl_async_abort_404')(test_acl_async_abort_404)
    app.route('/test_acl_async_abort_404')(test_acl_async_abort_404)

    #@app.route('/test_no_acl_abort_500')
    #@app.route('/test_acl_abort_500')
    def test_acl_abort_500(request):
        raise ServerError("")
    app.route('/test_no_acl_abort_500')(test_acl_abort_500)
    app.route('/test_acl_abort_500')(test_acl_abort_500)

    @app.route('/test_acl_uncaught_exception_500')
    def test_acl_uncaught_exception_500(request):
        raise Exception("This could've been any exception")

    @app.route('/test_no_acl_uncaught_exception_500')
    def test_no_acl_uncaught_exception_500(request):
        raise Exception("This could've been any exception") 
Example #6
Source File: test_exception_interception.py    From sanic-cors with MIT License 5 votes vote down vote up
def test_acl_exception_with_error_handler(self):
        '''
            If a 500 handler is setup by the user, responses should have
            CORS matching rules applied, regardless of whether or not
            intercept_exceptions is enabled.
        '''
        return_string = "Simple error handler"

        @self.app.exception(NotFound, ServerError, Exception)
        def catch_all_handler(request, exception):
            '''
                This error handler catches 404s and 500s and returns
                status 200 no matter what. It is not a good handler.
            '''
            return text(return_string)

        acl_paths = [
            '/test_acl_abort_404',
            '/test_acl_abort_500',
            '/test_acl_uncaught_exception_500'
        ]
        no_acl_paths = [
            '/test_no_acl_abort_404',
            '/test_no_acl_abort_500',
            '/test_no_acl_uncaught_exception_500'
        ]

        def get_with_origins(path):
            response = self.get(path, origin='www.example.com')
            return response

        for resp in map(get_with_origins, acl_paths):
            self.assertEqual(resp.status, 200)
            self.assertTrue(ACL_ORIGIN in resp.headers)

        for resp in map(get_with_origins, no_acl_paths):
            self.assertEqual(resp.status, 200)
            self.assertFalse(ACL_ORIGIN in resp.headers) 
Example #7
Source File: test_exception_interception.py    From sanic-cors with MIT License 5 votes vote down vote up
def test_acl_exception_with_error_handler(self):
        '''
            If a 500 handler is setup by the user, responses should have
            CORS matching rules applied, regardless of whether or not
            intercept_exceptions is enbaled.
        '''
        return_string = "Simple error handler"

        @self.app.exception(ServerError, NotFound, Exception)
        # Note, async error handlers don't work in Sanic yet.
        # async def catch_all_handler(request, exception):
        def catch_all_handler(request, exception):
            '''
                This error handler catches 404s and 500s and returns
                status 200 no matter what. It is not a good handler.
            '''
            return text(return_string, 200)

        acl_paths = [
            '/test_acl_abort_404',
            '/test_acl_abort_500'
        ]
        no_acl_paths = [
            '/test_no_acl_abort_404',
            '/test_no_acl_abort_500',
            '/test_no_acl_uncaught_exception_500',
            '/test_acl_uncaught_exception_500'
        ]
        def get_with_origins(path):
            return self.get(path, origin='www.example.com')

        for resp in map(get_with_origins, acl_paths):
            self.assertEqual(resp.status, 200)
            self.assertTrue(ACL_ORIGIN in resp.headers)

        for resp in map(get_with_origins, no_acl_paths):
            self.assertEqual(resp.status, 200)
            self.assertFalse(ACL_ORIGIN in resp.headers) 
Example #8
Source File: interactive.py    From rasa_core with Apache License 2.0 5 votes vote down vote up
def start_visualization(image_path: Text = None) -> None:
    """Add routes to serve the conversation visualization files."""

    app = Sanic(__name__)

    # noinspection PyUnusedLocal
    @app.exception(NotFound)
    async def ignore_404s(request, exception):
        return response.text("Not found", status=404)

    # noinspection PyUnusedLocal
    @app.route(VISUALIZATION_TEMPLATE_PATH, methods=["GET"])
    def visualisation_html(request):
        return response.file(visualization.visualization_html_path())

    # noinspection PyUnusedLocal
    @app.route("/visualization.dot", methods=["GET"])
    def visualisation_png(request):
        try:
            headers = {'Cache-Control': "no-cache"}
            return response.file(os.path.abspath(image_path), headers=headers)
        except FileNotFoundError:
            return response.text("", 404)

    app.run(host='0.0.0.0', port=DEFAULT_SERVER_PORT + 1, access_log=False)


# noinspection PyUnusedLocal 
Example #9
Source File: test_blueprints.py    From sanic with MIT License 5 votes vote down vote up
def test_bp_exception_handler(app):
    blueprint = Blueprint("test_middleware")

    @blueprint.route("/1")
    def handler_1(request):
        raise InvalidUsage("OK")

    @blueprint.route("/2")
    def handler_2(request):
        raise ServerError("OK")

    @blueprint.route("/3")
    def handler_3(request):
        raise NotFound("OK")

    @blueprint.exception(NotFound, ServerError)
    def handler_exception(request, exception):
        return text("OK")

    app.blueprint(blueprint)

    request, response = app.test_client.get("/1")
    assert response.status == 400

    request, response = app.test_client.get("/2")
    assert response.status == 200
    assert response.text == "OK"

    request, response = app.test_client.get("/3")
    assert response.status == 200 
Example #10
Source File: checks.py    From pubgate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def user_check(handler=None):
    @wraps(handler)
    async def wrapper(request, *args, **kwargs):
        user = await User.find_one(dict(name=kwargs["user"].lower()))
        if not user:
            raise exceptions.NotFound("User not found")

        kwargs["user"] = user
        return await handler(request, *args, **kwargs)
    return wrapper 
Example #11
Source File: checks.py    From pubgate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def outbox_check(handler=None):
    @wraps(handler)
    async def wrapper(request, *args, **kwargs):

        data = await Outbox.find_one(dict(user_id=kwargs["user"].name, _id=kwargs["entity"]))
        if not data:
            raise exceptions.NotFound("Object not found")

        kwargs["entity"] = data
        return await handler(request, *args, **kwargs)
    return wrapper 
Example #12
Source File: test_exceptions_handler.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def handler_3(request):
    raise NotFound("OK") 
Example #13
Source File: test_exceptions.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def handler_404(request):
    raise NotFound("OK") 
Example #14
Source File: test_blueprints.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_bp_exception_handler():
    app = Sanic('test_middleware')
    blueprint = Blueprint('test_middleware')

    @blueprint.route('/1')
    def handler_1(request):
        raise InvalidUsage("OK")

    @blueprint.route('/2')
    def handler_2(request):
        raise ServerError("OK")

    @blueprint.route('/3')
    def handler_3(request):
        raise NotFound("OK")

    @blueprint.exception(NotFound, ServerError)
    def handler_exception(request, exception):
        return text("OK")

    app.blueprint(blueprint)

    request, response = sanic_endpoint_test(app, uri='/1')
    assert response.status == 400


    request, response = sanic_endpoint_test(app, uri='/2')
    assert response.status == 200
    assert response.text == 'OK'

    request, response = sanic_endpoint_test(app, uri='/3')
    assert response.status == 200 
Example #15
Source File: interactive.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def start_visualization(image_path: Text = None) -> None:
    """Add routes to serve the conversation visualization files."""

    app = Sanic(__name__)

    # noinspection PyUnusedLocal
    @app.exception(NotFound)
    async def ignore_404s(request, exception):
        return response.text("Not found", status=404)

    # noinspection PyUnusedLocal
    @app.route(VISUALIZATION_TEMPLATE_PATH, methods=["GET"])
    def visualisation_html(request):
        return response.file(visualization.visualization_html_path())

    # noinspection PyUnusedLocal
    @app.route("/visualization.dot", methods=["GET"])
    def visualisation_png(request):
        try:
            headers = {"Cache-Control": "no-cache"}
            return response.file(os.path.abspath(image_path), headers=headers)
        except FileNotFoundError:
            return response.text("", 404)

    update_sanic_log_level()

    app.run(host="0.0.0.0", port=DEFAULT_SERVER_PORT + 1, access_log=False)


# noinspection PyUnusedLocal 
Example #16
Source File: test_plugin_exception.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def handler_3(request):
    raise NotFound("OK") 
Example #17
Source File: test_exceptions_handler.py    From sanic with MIT License 5 votes vote down vote up
def handler_3(request):
    raise NotFound("OK") 
Example #18
Source File: router.py    From sanic with MIT License 4 votes vote down vote up
def _get(self, url, method, host):
        """Get a request handler based on the URL of the request, or raises an
        error.  Internal method for caching.

        :param url: request URL
        :param method: request method
        :return: handler, arguments, keyword arguments
        """
        url = unquote(host + url)
        # Check against known static routes
        route = self.routes_static.get(url)
        method_not_supported = MethodNotSupported(
            f"Method {method} not allowed for URL {url}",
            method=method,
            allowed_methods=self.get_supported_methods(url),
        )

        if route:
            if route.methods and method not in route.methods:
                raise method_not_supported
            match = route.pattern.match(url)
        else:
            route_found = False
            # Move on to testing all regex routes
            for route in self.routes_dynamic[url_hash(url)]:
                match = route.pattern.match(url)
                route_found |= match is not None
                # Do early method checking
                if match and method in route.methods:
                    break
            else:
                # Lastly, check against all regex routes that cannot be hashed
                for route in self.routes_always_check:
                    match = route.pattern.match(url)
                    route_found |= match is not None
                    # Do early method checking
                    if match and method in route.methods:
                        break
                else:
                    # Route was found but the methods didn't match
                    if route_found:
                        raise method_not_supported
                    raise NotFound(f"Requested URL {url} not found")

        kwargs = {
            p.name: p.cast(value)
            for value, p in zip(match.groups(1), route.parameters)
        }
        route_handler = route.handler
        if hasattr(route_handler, "handlers"):
            route_handler = route_handler.handlers[method]
        return route_handler, [], kwargs, route.uri, route.name 
Example #19
Source File: extension.py    From sanic-cors with MIT License 4 votes vote down vote up
def wrapper(cls, f, ctx, req, e):
        opts = ctx.options
        log = ctx.log
        # get response from the original handler
        if (req is not None and SANIC_19_12_0 <= SANIC_VERSION and
              isinstance(e, MethodNotSupported) and req.method == "OPTIONS" and
              opts.get('automatic_options', True)):
            # A very specific set of requirments to trigger this kind of
            # automatic-options resp
            resp = response.HTTPResponse()
        else:
            do_await = iscoroutinefunction(f)
            resp = f(req, e)
            if do_await:
                log(logging.DEBUG,
                    "Found an async Exception handler response. "
                    "Cannot apply CORS to it. Passing it on.")
                return resp
        # SanicExceptions are equiv to Flask Aborts,
        # always apply CORS to them.
        if (req is not None and resp is not None) and \
                (isinstance(e, exceptions.SanicException) or
                 opts.get('intercept_exceptions', True)):
            try:
                cls._apply_cors_to_exception(ctx, req, resp)
            except AttributeError:
                # not sure why certain exceptions doesn't have
                # an accompanying request
                pass
        if req is None:
            return resp
        # These exceptions have normal CORS middleware applied automatically.
        # So set a flag to skip our manual application of the middleware.
        try:
            request_context = ctx.request[id(req)]
        except (LookupError, AttributeError):
            # On Sanic 19.12.0, a NotFound error can be thrown _before_
            # the request_context is set up. This is a fallback routine:
            if SANIC_19_12_0 <= SANIC_VERSION and \
                    isinstance(e, (NotFound, MethodNotSupported)):
                # On sanic 19.9.0+ request is a dict, so we can add our
                # flag directly to it.
                request_context = req.ctx
            else:
                log(logging.DEBUG,
                    "Cannot find the request context. Is request started? "
                    "Is request already finished?")
                request_context = None
        if request_context is not None:
            setattr(request_context,
                    SANIC_CORS_SKIP_RESPONSE_MIDDLEWARE, "1")
        return resp