问题描述
我正在使用Django 1.10,并尝试使用异常中间件捕获所有异常。
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
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
middleware.py
from django.http import HttpResponse
class ExceptionMiddleware(object):
def process_exception(self, request, exception):
return HttpResponse("in exception")
我有看到这些,并且还有其他关于中间件和Middleware_classes的问题,但是我不确定这对这种情况如何适用,或者我为解决该问题实际需要进行哪些更改。
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.
推荐答案
由于您使用的是新的 MIDDLEWARE
设置,因此您的中间件类必须接受 get_response
参数:
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
您可以这样编写课程:
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")
您还可以使用 MiddlewareMixin
使您的中间件与1.10之前和1.10之后的Django版本兼容:
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")
这篇关于Django异常中间件:TypeError:object()不带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!