Last active
May 26, 2022 07:17
-
-
Save blacksmithop/e66a1473070302e5daf0623669350c39 to your computer and use it in GitHub Desktop.
django - require http methods (restframework)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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." |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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