Theron Luhn
Theron Luhn

Reputation: 4082

Pyramid: Custom 404 page returns as "200 OK"

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?

Upvotes: 18

Views: 5751

Answers (4)

Michael Kennedy
Michael Kennedy

Reputation: 3380

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

Upvotes: 0

ajorquera
ajorquera

Reputation: 1309

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

Upvotes: 8

Michael Merickel
Michael Merickel

Reputation: 23331

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

Upvotes: 21

turtlebender
turtlebender

Reputation: 1907

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

Upvotes: 0

Related Questions