Login

Decorator that limits request methods

Author:
schinckel
Posted:
July 25, 2009
Language:
Python
Version:
1.0
Tags:
decorator request
Score:
-2 (after 2 ratings)

I wanted to be able to limit which types of requests a view will accept. For instance, if a view only wants to deal with GET requests.

@methods(GET)
def index(request):
    # do stuff

Now, calling this view with a non-GET request will cause a 403.

You can easily change this to a 404, by using a different return function: which you may wish to do with openly available sites, as a 403 indicates there is a resource present.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from django.http import HttpResponseForbidden

    class methods(object):
        def __init__(self, *methods):
            self.methods = methods
    
        def __call__(self, f):
            def wrapped_f(request, *args):
                if request.method not in self.methods:
                    return HttpResponseForbidden('')
                return f(request, *args)
            return wrapped_f
    
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    DELETE = "DELETE"
    HEAD = "HEAD"
    OPTIONS = "OPTIONS"
    TRACE = "TRACE"
    CONNECT = "CONNECT"

More like this

  1. Use memcached to throttle POSTs by coleifer 5 years ago
  2. PK->objects in view signature by AdamKG 7 years, 1 month ago
  3. Decorator to limit request rates to individual views by jensbreit 6 years, 8 months ago
  4. Gzip decorator by SmileyChris 6 years, 10 months ago
  5. limit view request rate decorator by anatoliy.larin 6 years ago

Comments

dc (on July 25, 2009):

from django.views.decorators import require_http_methods

#

dc (on July 25, 2009):

Sorry

from django.views.decorators.http import require_http_methods

#

schinckel (on July 26, 2009):

Nice to know my code is virtually identical. Makes me think I picked the right way to do it.

:)

#

schinckel (on August 17, 2009):

This snippet only works with view functions. I have been doing some stuff with views that are methods of a class (think of an API that is analogous to django.contrib.admin, and we want some views to be methods of ModelApi, so they can be overridden), and this type of decorator doesn't quite work.

#

Please login first before commenting.