自定义金字塔错误消息
我正在尝试找到一种在金字塔应用程序中自定义错误消息(404、403)的方法。我找到了此文档,但目前还不清楚如何做到这一点。
我需要做什么来呈现模板之一(例如 templates/404.pt)而不是标准 404 消息。我在我的 __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()
其中 error_views.notfound 看起来像
def notfound(request):
macros = get_template('../templates/macros.pt')
return {
'macros': macros,
'title': "HTTP error 404"
}
当然它不起作用(在这种情况下如何指定模板名称?),甚至更多:看起来视图是根本没有被调用并且它的代码被忽略。
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 error_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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将
pyramid.exceptions
异常作为上下文传递给 add_view,而不是pyramid.httpexceptions
异常。这对我有用:
You should pass to add_view as context a
pyramid.exceptions
exception, not apyramid.httpexceptions
one.This works for me:
将其放入您的 myapp.views.errors 文件中:
让我知道这是否适合您。
Put this in your myapp.views.errors file:
Let me know if this works for you.
从 Pyramid 1.3 开始,使用
@notfound_view_config
装饰器就足够了。现在不需要在 __init__.py 中设置任何内容。有views.py的示例代码: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: