忽略不匹配预定义路由的请求

问题描述 投票:0回答:1

嗨,我有一些 Sanic python 应用程序代码,其中定义了以下路由


def create_inspector(app):
    inspector = Sanic(configure_logging=False)
    inspector.config['KEEP_ALIVE'] = False
    inspector.app = app
    inspector.add_route(render_status, '/')
    inspector.add_route(get_status, '/api/status')
    return inspector

但是当我用端点到达端点时

curl -k http://localhost:9504/api/123

我在应用程序日志中得到以下回溯

  File "/opt/product/4.0.0.1/lib64/python3.6/site-packages/sanic/app.py", line 546, in handle_request
    handler, args, kwargs, uri = self.router.get(request)
  File "/opt/product/4.0.0.1/lib64/python3.6/site-packages/sanic/router.py", line 344, in get
    return self._get(request.path, request.method, '')
  File "/opt/product/4.0.0.1/lib64/python3.6/site-packages/sanic/router.py", line 393, in _get
    raise NotFound('Requested URL {} not found'.format(url))
sanic.exceptions.NotFound: Requested URL /api/123 not found

是否可以捕获所有无效端点并将其发送到 404(资源未找到)状态。

python rest crud sanic
1个回答
0
投票

我必须修改我的代码如下

def create_inspector(app):
    inspector = Sanic(configure_logging=False)
    inspector.config['KEEP_ALIVE'] = False
    inspector.app = app
    inspector.add_route(render_status, '/')
    inspector.add_route(not_found, r"<path:path>") # this was added here
    inspector.add_route(get_status, '/api/status')

    return inspector

async def not_found(request, path): #new fn was added to handle non existent path
    return json('Not Found', status=404)
© www.soinside.com 2019 - 2024. All rights reserved.