当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.NotFound方法代码示例

本文整理汇总了Python中sanic.exceptions.NotFound方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.NotFound方法的具体用法?Python exceptions.NotFound怎么用?Python exceptions.NotFound使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sanic.exceptions的用法示例。


在下文中一共展示了exceptions.NotFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_middleware_response_exception

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:huge-success,项目名称:sanic,代码行数:21,代码来源:test_middleware.py

示例2: get

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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, "") 
开发者ID:huge-success,项目名称:sanic,代码行数:21,代码来源:router.py

示例3: token_get

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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}) 
开发者ID:autogestion,项目名称:pubgate,代码行数:20,代码来源:user.py

示例4: test_middleware_response_exception

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:ashleysommer,项目名称:sanicpluginsframework,代码行数:24,代码来源:test_plugin_middleware.py

示例5: handler_3

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
def handler_3(request):
    raise NotFound("OK") 
开发者ID:huge-success,项目名称:sanic,代码行数:4,代码来源:test_exceptions_handler.py

示例6: test_bp_exception_handler

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:huge-success,项目名称:sanic,代码行数:32,代码来源:test_blueprints.py

示例7: add_routes

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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") 
开发者ID:ashleysommer,项目名称:sanic-cors,代码行数:31,代码来源:test_exception_interception.py

示例8: test_acl_exception_with_error_handler

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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) 
开发者ID:ashleysommer,项目名称:sanic-cors,代码行数:40,代码来源:test_exception_interception.py

示例9: start_visualization

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:RasaHQ,项目名称:rasa_core,代码行数:30,代码来源:interactive.py

示例10: user_check

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:autogestion,项目名称:pubgate,代码行数:12,代码来源:checks.py

示例11: outbox_check

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:autogestion,项目名称:pubgate,代码行数:13,代码来源:checks.py

示例12: handler_404

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
def handler_404(request):
    raise NotFound("OK") 
开发者ID:hhstore,项目名称:annotated-py-projects,代码行数:4,代码来源:test_exceptions.py

示例13: test_bp_exception_handler

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:hhstore,项目名称:annotated-py-projects,代码行数:34,代码来源:test_blueprints.py

示例14: start_visualization

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:botfront,项目名称:rasa-for-botfront,代码行数:32,代码来源:interactive.py

示例15: _get

# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import NotFound [as 别名]
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 
开发者ID:huge-success,项目名称:sanic,代码行数:54,代码来源:router.py


注:本文中的sanic.exceptions.NotFound方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。