gpt4 book ai didi

python - 自定义 Pyramid 错误消息

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:50 26 4
gpt4 key购买 nike

我正在尝试找到一种方法来在我的 Pyramid 应用程序中自定义错误消息 (404, 403)。我找到了 this doc , 但仍然不清楚如何去做。

我需要做什么来呈现模板之一(例如,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"
}

确定它不起作用(在这种情况下我如何指定模板名称?),甚至更多:似乎根本没有调用 View 并且它的代码被忽略了。

最佳答案

您应该将 pyramid.exceptions 异常作为上下文传递给 add_view,而不是 pyramid.httpexceptions

这对我有用:

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')

关于python - 自定义 Pyramid 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6747735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com