How do I return a 401 Unauthorized in Django?

PythonDjango

Python Problem Overview


Instead of doing this:

res = HttpResponse("Unauthorized")
res.status_code = 401
return res

Is there a way to do it without typing it every time?

Python Solutions


Solution 1 - Python

I know this is an old one, but it's the top Google result for "django 401", so I thought I'd point this out...

Assuming you've already imported django.http.HttpResponse, you can do it in a single line:

return HttpResponse('Unauthorized', status=401)

The 'Unauthorized' string is optional. Easy.

Solution 2 - Python

class HttpResponseUnauthorized(HttpResponse):
    status_code = 401

...
return HttpResponseUnauthorized()

Normally, you should set the instance in __init__ or you end up with class variables that are shared between all instances. However, Django does this for you already:

class HttpResponse(object):
    """A basic HTTP response, with content and dictionary-accessed headers."""

    status_code = 200

    def __init__(self, content='', mimetype=None, status=None,
            content_type=None):
        # snip...
        if status:
            self.status_code = status

(see the Django code in context)

Solution 3 - Python

Inheritance solution

from django.http import HttpResponse

class Http401(HttpResponse):
    def __init__(self):
        super().__init__('401 Unauthorized', status=401)

in a util.py to replace multiple calls to:

return HttpResponse('401 Unauthorized', status=401)

with just:

return Http401()

Interestingly there are other named responses in 1.9.6 https://github.com/django/django/blob/1.9.6/django/http/response.py#L443 but not 401.

Solution 4 - Python

class HttpResponseUnauthorized(HttpResponse):
    def __init__(self):
        self.status_code = 401

...
return HttpResponseUnauthorized()

Solution 5 - Python

Write a view decorator that checks the appropriate HTTP headers and returns the appropriate response (there is no http://docs.djangoproject.com/en/dev/ref/request-response/#httpresponse-subclasses">built-in type for response code 401).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - PythonStu CoxView Answer on Stackoverflow
Solution 2 - PythonWilfred HughesView Answer on Stackoverflow
Solution 3 - PythonCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 4 - PythonGlenn MaynardView Answer on Stackoverflow
Solution 5 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow