Login

Decorator that limits request methods

Author:
schinckel
Posted:
July 25, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months 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.