Login

HTTP method_required Decorator

Author:
AdamKG
Posted:
March 29, 2008
Language:
Python
Version:
.96
Score:
-1 (after 1 ratings)

Edit: As James pointed out, django.views.decorators.http already provides stuff for this. Use that instead.

Old description: Should be pretty straightforward; you give it the method you can accept, it returns 405's for other methods. EG, @method_required("POST") at the top of your view.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def method_required(method):
    """
    Decorator factory that limits a view to a particular HTTP method. 
    """
    from django.http import HttpResponseNotAllowed
    def _decorator(func):
        def _closure(request, *args, **kwargs):
            if not request.method==method:
                return HttpResponseNotAllowed([method])
            else:
                return func(request, *args, **kwargs)
        _closure.__name__ = func.__name__
        _closure.__doc___ = func.__doc__
        _closure.__module___ = func.__module__
        return _closure
    return _decorator

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.