Login

HTTP method_required Decorator

Author:
AdamKG
Posted:
March 29, 2008
Language:
Python
Version:
.96
Tags:
http decorator
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. Stales Cache Class Method Decorator by amitu 6 years, 8 months ago
  2. Decorate class-based views with regular decorators by jeffheard 6 months, 1 week ago
  3. Decorating URL includes by cotton 3 years, 10 months ago
  4. "Autoconnect" model decorator, easy pre_save and post_save signal connection by bendavis78 4 years, 11 months ago
  5. Automatic Memoization Decorator by nikmolnar 2 years, 6 months ago

Comments

Please login first before commenting.