I'm trying to find a way to customize error messages (404, 403) in my Pyramid application. I've found this doc, but it's still not clear how to do it.
What I need to do it to render one of the templates (say, templates/404.pt) instead of standard 404 message. I've added following to my __init__.py
:
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPNotFound
import myapp.views.errors as error_views
<...>
def main(global_config, **settings):
config = Configurator(settings=settings)
config.add_static_view('static', 'myapp:static')
config.add_route(...)
<...>
config.add_view(error_views.notfound, context=HTTPNotFound)
return config.make_wsgi_app()
Where er开发者_C百科ror_views.notfound looks like
def notfound(request):
macros = get_template('../templates/macros.pt')
return {
'macros': macros,
'title': "HTTP error 404"
}
Sure it does not works (how do I specify template name in this case?), and even more: it seems view is not called at all and it's code ignored.
You should pass to add_view as context a pyramid.exceptions
exception, not a pyramid.httpexceptions
one.
This works for me:
def main(global_config, **settings):
"""
This function returns a Pyramid WSGI application.
"""
...
config.add_view('my_app.error_views.not_found_view',
renderer='myapp:templates/not_found.pt',
context='pyramid.exceptions.NotFound')
Put this in your myapp.views.errors file:
from pyramid.renderers import render_to_response
def notfound(request):
context['title'] = "HTTP error 404"
return render_to_response('../templates/macros.pt', context)
Let me know if this works for you.
From Pyramid 1.3 it's enough to use @notfound_view_config
decorator. There is no need to set anything in __init__.py
now. There is example code for views.py:
from pyramid.view import notfound_view_config
@notfound_view_config(renderer='error-page.mako')
def notfound(request):
request.response.status = 404
return {}
精彩评论