Pyramid: Custom 404 page returns as “200 OK”

半世苍凉 提交于 2019-11-29 16:43:55

问题


I have a custom 404 view defined in my Pyramid app:

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

It works fine, except that the HTTP status code sent with the content is 200 OK, which is not OK by any means. I'm having the same problem with 403 Forbidden. How can I get Pyramid to send the correct status code?


回答1:


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 {}



回答2:


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



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/9815224/pyramid-custom-404-page-returns-as-200-ok

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