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.
-
Do you want to run a same piece of code for every api for GET/POST/PUT method ? or just one API's GET/POST/PUT method?Rong Zhao– Rong Zhao2017-01-12 07:20:56 +00:00Commented Jan 12, 2017 at 7:20
-
same for Get and post.. different for Put. A solution for same for all methods would also be appreciated.Manasvi Batra– Manasvi Batra2017-01-12 07:26:45 +00:00Commented Jan 12, 2017 at 7:26
Add a comment
|
2 Answers
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.
Comments
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.
4 Comments
Manasvi Batra
Thanks for this solution, but I don't want to use middleware. I just wanted to know if a simple and direct solution exists for this.
Sayse
Using a middleware would cripple your website for this kind of use. it would be ran for every request - regardless of this simple use case
Rong Zhao
Got it... In my mind, middleware is flexible enough, you could handle all api or just one api at this place. Good luck to find the method you want : )
Rong Zhao
@Sayse, yes, it will affect performance. but we could judge the path at the first line. if the path is not target api, skip....