Skip to content

Instantly share code, notes, and snippets.

@blacksmithop
Last active May 26, 2022 07:17
Show Gist options
  • Save blacksmithop/e66a1473070302e5daf0623669350c39 to your computer and use it in GitHub Desktop.
Save blacksmithop/e66a1473070302e5daf0623669350c39 to your computer and use it in GitHub Desktop.
django - require http methods (restframework)
from functools import wraps
from django.http import HttpResponseNotAllowed
def require_http_methods(method_list):
"""
Decorator to make a view only accept particular request methods. Usage::
@require_http_methods(["GET", "POST"])
def my_view(request):
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
if request.method not in method_list:
response = HttpResponseNotAllowed(method_list)
return response
return func(request, *args, **kwargs)
return inner
return decorator
require_GET = require_http_methods(["GET"])
require_GET.__doc__ = "View only accepts the GET method."
from .decorators import require_http_methods, require_GET
@require_GET
def getAll(request):
...
@require_http_methods(["DELETE"])
def deleteById(request, id=None):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment