我正在尝试为我的django应用程序编写一些中间件。在docs中,它使用两个参数(请求和响应)定义流程响应。但是当我尝试编写一些中间件时,我会抛出一个异常:
Type Error:
process_response() takes 2 positional arguments but 3 were given
这是我的代码:
来自django.http import HttpResponseRedirect
class Middleware(object):
def process_response(self, request, response):
print('processing response')
ref = request.GET.get('ref','')
if ref:
response.set_cookie('ref', ref, max_age=3600*24*365)
return response
def process_request(request):
print('processing request')
print(request.META['PATH_INFO'])
ref = request.COOKIES.get('ref','')
if ref:
request.GET['ref'] = ref
return None
但后来发生了一件奇怪的事情。我注释掉了process_request函数。然后我得到了0个错误。当我取消注释process_request函数时,我得到了错误:
process_request() takes 1 positional argument but 2 were given
这开始看似随机行为..
答案 0 :(得分:2)
您在self
定义中遗漏了process_request
。