2012-03-22 46 views
16

我在金字塔的应用程序定义一个自定义的404视图:金字塔:自定义404名错误页面返回的“200 OK”

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

它工作正常,除了与内容发送的HTTP状态代码是200 OK ,这是不行的。我与403 Forbidden有同样的问题。我怎样才能让金字塔发送正确的状态码?

回答

19

例外视图链接的页面取的例子是,它提供了光点FO一个单独的视图你可以做任何你想做的事情。就像任何使用渲染器的视图一样,您可以通过request.response影响响应对象以修改其行为。渲染器然后填充身体。

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

完美!但是,一个更正:状态应该是'404 Not Found'。从金字塔文档:“response.status - 响应代码加上原因消息,如'200 OK'要设置没有消息的代码,请使用status_int ,即:response.status_int = 200.“ – 2012-03-22 02:41:49

+3

如果你se把它作为一个整数,它将在其内部查找表中查找状态并为你填充字符串。这是一个方便的皱纹,可能应该记录得更好。 – 2012-03-22 03:56:52

0

做到这一点,最好的办法就是覆盖默认未找到查看:

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

即使在这种情况下,您需要返回其具有404状态正确的响应对象:

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

向来自上述

+0

但是,这并不让我用一个变色龙模板... :( – 2012-03-22 01:43:53

+0

你可以,你自己呈现模板,或者,我相信变色龙渲染器将让你返回一个Response对象和那么,如果你做了你上面发布的内容,但是返回Response(status ='404 Not Found'),我相信它会通过变色龙提供一个空的字典并带有正确的响应代码。 – turtlebender 2012-03-22 02:19:09

6

实际上,在金字塔1.3有一个新的装饰@notfound_view_config。

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

下面是如何直接使用404钩子并呈现模板的过程。

在你INIT的.py:

config.add_notfound_view(not_found) 

在你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) 

我这样做是为了谈Python的对我说:​​,这里是一个无效的页面看到自定义模板呈现。

http://www.talkpythontome.com/there_is_no_cat