Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

http status code 404 - Django custom handler404 shows 404 but gives header 200

I made a custom handler404 for a authenticated Django website to avoid information leakage.

def check_logged_in_404(request):
    """ Custom 404. Show friendly 404 when logged in and redirect to /login
    when not logged in.
    """
    if request.user.is_authenticated():
        return render_to_response('404.html')
    else:
        return HttpResponseRedirect('/login')

Functionally it does exactly what I want. However the 404 return page has a status 200, which is correct code-wise. But this obviously needs to be a 404 return status.

A raise404 doesn't work because, if not ending in a infinite recursion, it comes back here and thus results in the same issue.

I tried a HttpResponseNotFound, but this only takes a string as a argument and not a template, which is not to DRY-ish.

And I manually tried to set the header with:

    response = render_to_response('404.html')
    response['Status'] = "Not Found - 404"
    return response

Then the status header is indeed set but the browser still shows up a 200.

I'm out of options .. Anybody that has tips, please be my hero ... :)

Thanx and regards,

Gerard.

Edit: I tried the status field value in all sort btw, but no luck :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd use render_to_string and HttpResponseNotFound, e.g. return HttpResponseNotFound(render_to_string('404.html')).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...