【问题标题】:Getting missing positional argument error when trying to define middleware in Django尝试在 Django 中定义中间件时出现缺少位置参数错误
【发布时间】:2017-05-14 07:47:29
【问题描述】:

我正在尝试在 Django 1.10 项目中提出我自己的第一个中间件。目前遇到以下错误

TypeError: init() 缺少 1 个必需的位置参数: 'get_response'

我在middleware.py 中定义了中间件,如下所示:

从 zeon.utils 导入 RequestLogThread

class StartRestEndPointMiddleWare(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        request.request_log_id = RequestLogThread('send_contact', request.data).start()

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

我在试图找出问题所在时迷失了方向,因为一切似乎都符合doc。我真的很感激任何提示。

更新: 我把它放到 middle_classes 中:

MIDDLEWARE_CLASSES = [
    'zeon.middleware.StartRestEndPointMiddleWare',
]

【问题讨论】:

  • 你是放入MIDDLEWARE字典还是MIDDLEWARE_CLASSES字典?
  • 我已根据您的问题更新了问题

标签: django-middleware


【解决方案1】:

Django 在 1.10 中改变了中间件类的工作方式。新型中间件类属于MIDDLEWARE 列表,如下所示:

MIDDLEWARE = [
    'zeon.middleware.StartRestEndPointMiddleWare',
]

当您将中间件放入 MIDDLEWARE_CLASSES 时,它会被视为旧式中间件,其工作方式有所不同。更好的错误消息可能会更清楚地说明这一点。

【讨论】:

  • 其余的中间件呢?我是否应该将它们留在 MIDDLEWARE_CLASSES 中并仅将用户定义的中间件移动到 MIDDLEWARES ?或者我应该把所有东西都放到MIDDLEWARES
  • 看起来应该是MIDDLEWARE,而不是MIDDLEWARES
  • @EdgarNavasardyan:谢谢,已修复。所有内置中间件都支持两者,因此您可以将所有内容移至MIDDLEWARE。您不能同时拥有MIDDLEWAREMIDDLEWARE_CLASSES
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 2020-07-06
  • 2018-11-09
  • 2019-11-04
  • 2016-04-12
  • 1970-01-01
  • 2017-12-26
相关资源
最近更新 更多