Django exception middleware: TypeError: object() takes no parameters

和自甴很熟 提交于 2019-12-18 11:15:41

问题


I'm using Django 1.10 and trying to catch all exceptions with exception middleware.

The code below causes an internal server error:

mw_instance = middleware(handler)
TypeError: object() takes no parameters

views.py

from django.http import HttpResponse

def my_view(request):
    x = 1/0 # cause an exception
    return HttpResponse("ok")

settings.py

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',
    'myproject.middleware.ExceptionMiddleware',  

]

middleware.py

from django.http import HttpResponse

class ExceptionMiddleware(object):
    def process_exception(self, request, exception): 
        return HttpResponse("in exception")

I have seen these object() takes no parameters in django 1.10 and other questions talking about middleware versus middleware_classes, but I'm not sure how that applies to this case, or what I'd actually need to change to fix the issue.


回答1:


Since you are using the new MIDDLEWARE settings, your Middleware class must accept a get_response argument: https://docs.djangoproject.com/en/1.10/topics/http/middleware/#writing-your-own-middleware

You could write your class like this:

from django.http import HttpResponse

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

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

    def process_exception(self, request, exception): 
        return HttpResponse("in exception")

You could also use the MiddlewareMixin to make your Middleware compatible with pre-1.10 and post-1.10 Django versions: https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

class ExceptionMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        return HttpResponse("in exception")


来源:https://stackoverflow.com/questions/42232606/django-exception-middleware-typeerror-object-takes-no-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!