我正在努力让MiddleWare工作。我把它放在我的settings.py
:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'portal.middleware.SimpleMiddleware'
]
我在portal/middleware/MiddleWare.py
中实现了这个类:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
但是在跑步时,我得到TypeError
:
TypeError: __init__() takes exactly 2 arguments (1 given)
答案 0 :(得分:2)
由于您正在编写新式中间件,因此应在设置中使用MIDDLEWARE
而不是MIDDLEWARE_CLASSES
。
您还需要确保设置中的条目与中间件的位置匹配。条目'portal.middleware.SimpleMiddleware'
建议SimpleMiddleware
中的portal/middleware.py
课程与您的文件名portal/middleware/MiddleWare.py
不符。