Django中间件错误

时间:2017-09-03 04:24:22

标签: python django

我正在尝试通过引用示例here来编写自定义django中间件包:

from django.conf import settings

class StackOverflowMiddleware(object):
    def process_exception(self, request, exception):
        if settings.DEBUG:
            print exception.__class__.__name__
            print exception.message
        return None

并且位于venv/lib/python2.7/site-packages/django_error_assist/middleware.py

位置

我尝试在django设置中调用/包含此中间件,如下所示:

MIDDLEWARE = [
    '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',
    'django_error_assist.middleware.StackOverflowMiddleware', ]

但是我得到一个追溯,我一直在努力摆脱这样的追随:

File "/Users/Shyam/PycharmProjects/untitled/untitled/wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "/Users/Shyam/PycharmProjects/untitled/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
    return WSGIHandler()
  File "/Users/Shyam/PycharmProjects/untitled/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 151, in __init__
    self.load_middleware()
  File "/Users/Shyam/PycharmProjects/untitled/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 82, in load_middleware
    mw_instance = middleware(handler)
TypeError: object() takes no parameters

我哪里错了?任何线索/帮助将不胜感激。我正在尝试将这个中间件变成一个pip包。

我也做了我的作业,看了thisthis,当然还有官方的django link,但是我从错误的地方得不到多少帮助。

2 个答案:

答案 0 :(得分:2)

我建议您将所有将object改为MiddlewareMixin的课程。

class StackOverflowMiddleware(object):
    ....

为:

from django.utils.deprecation import MiddlewareMixin

class StackOverflowMiddleware(MiddlewareMixin):
    ....

答案 1 :(得分:1)

在版本1.10的Django中,中间件必须接受get_response agrument,请参阅docs。将您的班级更改为:

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

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

    def process_exception(self, request, exception):
        if settings.DEBUG:
            print exception.__class__.__name__
            print exception.message
        return None