如何实现SimpleMiddleware?

时间:2017-10-03 13:47:13

标签: django django-middleware

我正在努力让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)

1 个答案:

答案 0 :(得分:2)

由于您正在编写新式中间件,因此应在设置中使用MIDDLEWARE而不是MIDDLEWARE_CLASSES

您还需要确保设置中的条目与中间件的位置匹配。条目'portal.middleware.SimpleMiddleware'建议SimpleMiddleware中的portal/middleware.py课程与您的文件名portal/middleware/MiddleWare.py不符。