We are using the Pyramid framework, and have a custom 404 Not Found
handler:
@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}
This is fine for catching any POST or GET that is not explicitly handled by the traversal routing. However, there is a certain url pattern (api/*
) where it would be useful to have a completely different handler that we know can be stripped down to:
def not_found(self):
return {"error_message": "This endpoint is not supported by the api."}
However, I can't figure out how to set the view_config
to only catch context=HTTPNotFound
within the context of api/
. Note we are using traversal routing, so, we have an API
object that is in the traversal routing tree.
According to documentation any pyramid application can define multiple Not Found Views if necessary. This means that Not Found Views can carry predicates limiting their applicability.
For common use cases pyramid developers added special hooks. These sample hooks (pyramid >= 1.3) will get you the idea.
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')
For more advanced configuration I recommend using view configuration predicate arguments.