【问题标题】:Docker Python API Update method generates TypeError: unhashable type: 'dict'Docker Python API 更新方法生成 TypeError: unhashable type: 'dict'
【发布时间】:2021-07-03 09:49:48
【问题描述】:

Docker SDK for Python 说明 Container 对象类“容器”支持“更新”方法,文档中描述如下:


更新(**kwargs)
更新容器的资源配置。

参数:
blkio_weight (int) – 块 IO(相对权重),在 10 到 1000 之间
cpu_period (int) – 限制 CPU CFS(完全公平调度器)周期
cpu_quota (int) – 限制 CPU CFS(完全公平调度器)配额
cpu_shares (int) – CPU 份额(相对权重)
cpuset_cpus (str) – 允许执行的 CPU
cpuset_mems (str) – 允许执行的 MEM
mem_limit (int or str) – 内存限制
mem_reservation (int or str) – 内存软限制
memswap_limit(int 或 str)– 总内存(内存 + 交换),-1 禁用交换
kernel_memory (int or str) – 内核内存限制

restart_policy (dict) – 重启策略字典

  • 容器退出时重启。配置为带键的字典:

    • 名称:故障之一,或始终。
    • MaximumRetryCount:失败时重启容器的次数。
    • 例如:{"Name": "on-failure", "MaximumRetryCount": 5}

reference in docker python api doc

当尝试使用这个时:

client = docker.from_env()
for container in client.containers.list():
    restart_policy = {'restart_policy',{'MaximumRetryCount': 4, 'Name': 'on-failure'}}
    container.update(restart_policy)

我遇到了错误:

restart_policy = {'restart_policy',{'MaximumRetryCount': 4, 'Name': 'on-failure'}}
TypeError: unhashable type: 'dict'

请指导如何制定请求!

【问题讨论】:

  • 您提到了 restart_policy (dict) – 重启策略字典。在代码中 restart_policy 是 set 而不是 dict。可能是你的意思 - restart_policy = {'restart_policy': {'MaximumRetryCount': 4, 'Name': 'on-failure'}}
  • 感谢 Ram,当我按照建议更新时,返回错误如下:TypeError: update() takes 1 positional argument but 2 were given Rgds..

标签: python docker typeerror


【解决方案1】:

您应该将该参数作为函数调用中的命名参数传递:

container.update(restart_policy={'Name': 'on-failure', 'MaximumRetryCount': 4})

如果您出于某种原因需要将其作为单独的字典,则需要使用 **kwargs 语法传递该字典:

kwargs = {
  'restart_policy': {
    'Name': 'on-failure',
    'MaximumRetryCount': 4
  }
}
container.update(**kwargs)

{a, b} 使用逗号而不是冒号创建 Python set,其中 {'a': b} 创建 dict。没有**function(args) 将字典作为位置参数传递,function(**args) 扩展字典以传递命名参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-14
    • 2015-11-24
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2016-10-01
    相关资源
    最近更新 更多