嗨,我有一些 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(资源未找到)状态。
我必须修改我的代码如下
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)