__init __()缺少1个必需的位置参数:“ get_response”

时间:2019-06-07 14:22:27

标签: django

我使用Django 1.11并收到此错误

class TenantMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

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

我试图解决该问题:

class TenantMiddleware:
    def process_response(self, request, response):
        set_tenant_schema_for_request(request)
        return response

使用“新”中间件样式,这是否正确?

1 个答案:

答案 0 :(得分:2)

您的第一个示例是新型中间件的示例,第二个示例是旧式中间件的示例。如果您仍想在新型中间件中使用process_response(request, response),则应使用django.utils.deprecation.MiddlewareMixin类作为中间件类的父类。

from django.utils.deprecation import MiddlewareMixin

# old-style middleware usage in new versions of django
class TenantMiddleware(MiddlewareMixin):

    def process_response(self, request, response):
        set_tenant_schema_for_request(request)
        return response

如果您使用新型中间件,

# new-style middleware usage and explanation
class TenantMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # implement process_request(request) logic here
        response = self.get_response(request)
        # implement process_response(request, response) logic here
        return response # returns HttpResponse or subclasses here.

在新型中间件中,self.get_response(request)之前的代码与process_request(request)相同,self.get_response(request)之后的代码与process_response(request, response)相同。

希望,对您有帮助。