Настройка сообщений об ошибках Pyramid - PullRequest
3 голосов
/ 19 июля 2011

Я пытаюсь найти способ настроить сообщения об ошибках (404, 403) в моем приложении Pyramid. Я нашел этот документ , но до сих пор не ясно, как это сделать.

Что мне нужно сделать, чтобы отобразить один из шаблонов (скажем, 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 вообще не вызывается, и его код игнорируется.

Ответы [ 3 ]

2 голосов
/ 19 июля 2011

Вы должны передать add_view в качестве контекста исключение pyramid.exceptions, а не 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')
2 голосов
/ 15 февраля 2014

Из 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 голосов
/ 19 июля 2011

Поместите это в ваш файл 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)

Дайте мне знать, если это работает для вас.

...