【问题标题】:TypeError when logging kwargs记录 kwargs 时出现 TypeError
【发布时间】:2019-09-14 22:16:02
【问题描述】:

我在记录 kwargs 和 args 时遇到 TypeError。下面是我用来记录 kwargs 的 Django View 类的基类。

class CustomAPI(APIView):
    _url = None

    def initial(self, request, *args, **kwargs):
        logger.info("Request: %s, Args: %s, Kwargs: %s" % (request.__dict__, str(*args), str(**kwargs)))
        CustomAPI._url = request.get_full_path()
        super(CustomAPI, self).initial(request, *args, **kwargs)

错误日志显示以下错误-

文件“path/to/app/api_common.py”,第 55 行,初始 logger.info("请求: %s, Args: %s, Kwargs: %s" % (request.dict, str(*args), str(**kwargs))) TypeError: 'id' 是此函数的无效关键字参数

str(**kwargs) 有什么问题吗?

【问题讨论】:

  • CustomAPI 类是什么?您确定该请求正在由 APIProductDetails 类处理并且它不匹配不同的 URL 模式吗?请显示完整的回溯。
  • @Alasdair 感谢您的指点。是的,CustomAPI 导致了错误。但是我仍然很困惑为什么会发生这种情况。已在代码中添加详细信息。如果我正在评论记录器行,它工作正常。
  • 顺便说一句,CustomApi._url 不是线程安全的 - 如果您稍后回读 CustomApi._url,您可能会看到另一个请求写入的值。设置self._url 并稍后回读self._url 应该是安全的。
  • 感谢指点。将对此进行审核。

标签: python django-class-based-views


【解决方案1】:

目前,您拥有str(**kwargs)。如果kwargs{'id': '5'},这等效于str(id=5),这会引发TypeError,因为str 不接受id

如果你想要kwargs 字典的字符串表示,那么使用:

str(kwargs)

同样,str(*args) 如果len(args) > 1 将给出 TypeError。你应该使用:

str(args)

【讨论】:

    【解决方案2】:

    您应该通过方法的self.kwargs 而不是kwargs 访问参数。

    Django 实际上并没有直接调用你的方法。由于它动态创建类实例,因此不会像在基于函数的视图中那样访问kwargs。 DRF 视图只不过是 Django 通用视图,因此规则也适用于它们。

    【讨论】:

      【解决方案3】:

      或者你可以在方法中传递 id

      class APIProductDetails(CustomAPI):
      
          permission_classes = (CustomAuthentication,)
      
          def get(self, request, id):
              return Response(data={}, status=200)
      

      【讨论】:

        猜你喜欢
        • 2019-05-31
        • 1970-01-01
        • 1970-01-01
        • 2017-06-20
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 2018-06-17
        相关资源
        最近更新 更多