Pyramid: Custom 404 page returns as “200 OK”

旧时模样 提交于 2019-11-30 11:16:48

The exception view is a separate view that provides a spot for you to do whatever you want. Just like any view that uses a renderer, you can affect the response object via request.response to modify its behavior. The renderer then fills in the body.

@view_config(context=HTTPNotFound, renderer='404.pt')
def not_found(self, request):
    request.response.status = 404
    return {}

Actually, in pyramid 1.3 There's a new decorator @notfound_view_config.

@notfound_view_config(renderer = '404_error.jinja2')
def notfound(request):
    request.response.status = 404

The best way to do this is to override the default Not Found View:

http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/hooks.html#changing-the-not-found-view

Even in this scenario, you need to return a proper response object which has a status of 404:

def notfound(request):
    return Response('Not Found, dude', status='404 Not Found')

To take the example from the page linked above

Here is how you can directly use the 404 hook and render a template while doing so.

In your init.py:

config.add_notfound_view(not_found)

In your view.py:

from pyramid.view import notfound_view_config
from pyramid.renderers import render_to_response

def not_found(request):
    request.response.status = 404
    t = 'talk_python_to_me_com:templates/errors/404.pt'
    return render_to_response(t, {}, request)

I did this for Talk Python To Me: http://www.talkpythontome.com/, here's an invalid page to see a custom template rendered.

http://www.talkpythontome.com/there_is_no_cat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!