2017-09-03 63 views
1

我想參照的例子here編寫自定義Django的中間件組件: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包。

我也做了我的功課,看着this,this,當然還有官方的django link,但是我無法從這些方面得到很多幫助,因爲我在哪裏出錯了。

回答

1

從版本1.10開始的Django中間件必須接受get_response,參見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 
+1

謝謝您的回答。它像一個魅力。 –

1

我建議你更改了objectMiddlewareMixin所有類。

class StackOverflowMiddleware(object): 
    .... 

到:

from django.utils.deprecation import MiddlewareMixin 

class StackOverflowMiddleware(MiddlewareMixin): 
    .... 
+0

謝謝你的時間。我試了另一個答案,它的工作。 –