在特定视图中使用自定义中间件获取类型错误

Getting type-error using custom middleware in specific view

这是我的中间件

class HasAccessMiddleware(object):
    def __init__(self, get_response):
        print("init")
        self.get_response = get_response

    def __call__(self, request):
        allowed_ips = WebSettings.get_allowed_ip()
        ip = request.META.get('REMOTE_ADDR')  # Get client IP
        if ip not in allowed_ips:
            return HttpResponse("false", status.HTTP_401_UNAUTHORIZED)
        print("call")
        return self.get_response(request)

这是我的设置

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',
'tools.middleware.HasAccessMiddleware',

)

这是我的观点

@decorator_from_middleware(HasAccessMiddleware)
def json_backup(request):
    pass

我遇到了这个错误

TypeError: __init__() takes exactly 2 arguments (1 given)

你能帮我找出问题所在吗? 谢谢

如果只想在六个视图上使用这个,那就直接写成装饰器吧

def has_access(view_func):
    @functools.wraps(view_func)
    def wrapped(request, *args, **kwargs):
        allowed_ips = WebSettings.get_allowed_ip()
        ip = request.META.get('REMOTE_ADDR')  # Get client IP
        if ip not in allowed_ips:
            return HttpResponse("false", status.HTTP_401_UNAUTHORIZED)
        return view_func(request, *args, **kwargs)

现在您可以使用 @has_access 装饰您的视图。