Url-遍历路由未找到特定的 404
Url-Specific 404 Not Found With Traversal Routing
我们正在使用 Pyramid 框架,并且有一个自定义 404 Not Found
处理程序:
@view_config(request_method='GET', renderer='webapp:templates/pages/404.html', context=HTTPNotFound)
@view_config(request_method='POST', renderer='webapp:templates/pages/404.html', context=HTTPNotFound)
def not_found(self):
# Various (relatively) heavy-weight thinking occurs
return {"some_data": some_data}
这对于捕获遍历路由未明确处理的任何 POST 或 GET 来说很好。但是,有一个特定的 url 模式 (api/*
),其中有一个完全不同的处理程序会很有用,我们知道可以将其简化为:
def not_found(self):
return {"error_message": "This endpoint is not supported by the api."}
但是,我不知道如何将 view_config
设置为仅在 api/
的上下文中捕获 context=HTTPNotFound
。请注意,我们正在使用遍历路由,因此,我们在遍历路由树中有一个 API
对象。
According to documentation 任何金字塔应用程序都可以根据需要定义多个未找到的视图。这意味着未找到的视图可以携带限制其适用性的谓词。
对于常见的用例,金字塔开发人员添加了特殊的挂钩。这些示例钩子 (pyramid >= 1.3) 会让你明白。
from pyramid.view import notfound_view_config
@notfound_view_config(request_method='GET')
def notfound_get(request):
return Response('Not Found during GET, dude', status='404 Not Found')
@notfound_view_config(request_method='POST')
def notfound_post(request):
return Response('Not Found during POST, dude', status='404 Not Found')
@notfound_view_config(context='.your_package.api_class')
def notfound_post(request):
"""matches only when traversal returns an object of API class"""
return Response('Not Found during POST request on API endpoint, dude', status='404 Not Found')
对于更高级的配置,我建议使用 view configuration predicate arguments。
我们正在使用 Pyramid 框架,并且有一个自定义 404 Not Found
处理程序:
@view_config(request_method='GET', renderer='webapp:templates/pages/404.html', context=HTTPNotFound)
@view_config(request_method='POST', renderer='webapp:templates/pages/404.html', context=HTTPNotFound)
def not_found(self):
# Various (relatively) heavy-weight thinking occurs
return {"some_data": some_data}
这对于捕获遍历路由未明确处理的任何 POST 或 GET 来说很好。但是,有一个特定的 url 模式 (api/*
),其中有一个完全不同的处理程序会很有用,我们知道可以将其简化为:
def not_found(self):
return {"error_message": "This endpoint is not supported by the api."}
但是,我不知道如何将 view_config
设置为仅在 api/
的上下文中捕获 context=HTTPNotFound
。请注意,我们正在使用遍历路由,因此,我们在遍历路由树中有一个 API
对象。
According to documentation 任何金字塔应用程序都可以根据需要定义多个未找到的视图。这意味着未找到的视图可以携带限制其适用性的谓词。
对于常见的用例,金字塔开发人员添加了特殊的挂钩。这些示例钩子 (pyramid >= 1.3) 会让你明白。
from pyramid.view import notfound_view_config
@notfound_view_config(request_method='GET')
def notfound_get(request):
return Response('Not Found during GET, dude', status='404 Not Found')
@notfound_view_config(request_method='POST')
def notfound_post(request):
return Response('Not Found during POST, dude', status='404 Not Found')
@notfound_view_config(context='.your_package.api_class')
def notfound_post(request):
"""matches only when traversal returns an object of API class"""
return Response('Not Found during POST request on API endpoint, dude', status='404 Not Found')
对于更高级的配置,我建议使用 view configuration predicate arguments。