Reputation: 384
Is it possible to have a method in my APIView class which runs the same piece of code independent of the method i.e. GET/POST/PUT.
Upvotes: 2
Views: 1730
Reputation: 43320
As with Django, the APIView
works the same way by first going through the dispatch method before deciding which request method to use so you could override that in your own view
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
See dispatch methods for more information.
Upvotes: 2
Reputation: 318
Maybe you could use django Middleware to meet this requirement.
class CommonResponseMiddleware:
def __init__(self):
pass
def process_request(self, request):
path = request.path_info.lstrip('/')
method = request.method.upper()
if method == "DELETE":
request.META['REQUEST_METHOD'] = 'DELETE'
request.DELETE = QueryDict(request.body)
if method == "PUT":
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = QueryDict(request.body)
params = {}
if method == "GET":
params = request.GET.items()
# do what ever you want for GET method
if method == "POST":
params = request.POST.items()
# do what ever you want for POST method
if method == "PUT":
params = request.PUT.items()
# do what ever you want for PUT method
if method == "DELETE":
params = request.DELETE.items()
# do what ever you want for DELETE method
then apply this middleware in settings.py.
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware', # <--here
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'authentication.auth.middleware.LoginRequiredMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'core.middleware.CommonResponseMiddleware',
]
You could find more about middleware, hope it could help you.
Upvotes: 0