是否可以在我的APIView类中使用一个方法来运行与该方法无关的同一段代码,即GET / POST / PUT。
答案 0 :(得分:1)
与django一样,APIView
在决定使用哪种请求方法之前首先通过调度方法以相同的方式工作,因此您可以在自己的视图中覆盖它
def dispatch(self, request):
return super().dispatch(request)
有关详细信息,请参阅dispatch methods。
答案 1 :(得分:0)
也许你可以使用django Middleware来满足这个要求。
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
然后在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',
]
你可以找到更多关于中间件的信息,希望它可以帮助你。