自定义中间件类会引发错误

时间:2016-11-15 16:30:55

标签: python django django-middleware

我想创建一个非常简单的中间件,只需打印即可。在每个请求。问题是它会引发错误:

Traceback (most recent call last):
  File "c:\python27\Lib\wsgiref\handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\core\handlers\wsgi.py", line 170, in __call__
    self.load_middleware()
  File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\core\handlers\base.py", line 52, in load_middleware
    mw_instance = mw_class()
TypeError: __init__() takes exactly 2 arguments (1 given)

中间件类位于project/project/middleware.py

middleware.py

class UserHasProfileMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        print 'OK'
        return response

SETTINGS.PY

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'SolutionsForLanguages.middleware.UserHasProfileMiddleware'
)

你知道问题出在哪里吗?

1 个答案:

答案 0 :(得分:6)

Django在Django 1.10中引入了new-style middleware

您的UserHasProfileMiddleware是一种新型的中间件类。假设您使用的是Django 1.10+,则应使用MIDDLEWARE设置,而不是MIDDLEWARE_CLASSES。所有其他中间件都来自Django,因此重命名设置应该足以修复错误。

MIDDLEWARE = (
    ...
)

如果您使用的是Django 1.9或更早版本,则应将UserHasProfileMiddleware课转为old-style middleware