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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
from django.views.decorators import require_http_methods
#
Sorry
from django.views.decorators.http import require_http_methods
#
Nice to know my code is virtually identical. Makes me think I picked the right way to do it.
:)
#
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.