自定义Pyramid错误信息

3 投票
3 回答
2618 浏览
提问于 2025-04-16 21:50

我正在寻找一种方法来定制我在Pyramid应用中的错误信息(比如404和403错误)。我找到了一份文档,但还是不太清楚该怎么做。

我想要做的是在出现404错误时,显示一个自定义的模板(比如,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"
            }

当然,这并没有奏效(在这种情况下,我该如何指定模板名称呢?),更糟糕的是:似乎这个视图根本没有被调用,它的代码被忽略了。

3 个回答

2

从Pyramid 1.3开始,只需要使用 @notfound_view_config 这个装饰器就可以了。现在不需要在 __init__.py 文件中设置任何东西了。下面是views.py的示例代码:

from pyramid.view import notfound_view_config
@notfound_view_config(renderer='error-page.mako')
def notfound(request):
    request.response.status = 404
    return {}
2

把这个放到你的 myapp.views.errors 文件里:

from pyramid.renderers import render_to_response

def notfound(request):
    context['title'] = "HTTP error 404"
    return render_to_response('../templates/macros.pt', context)

如果这个对你有效,记得告诉我哦。

2

你应该把一个 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')

撰写回答