Python 应为类型为';dict';

Python 应为类型为';dict';,python,python-3.4,Python,Python 3.4,我试过了,但帮不了我多少忙,同样的错误仍然存在,我不知道是什么导致了下面代码中的问题 try: request = urllib.request.Request(url,data=payload,method='PUT',headers={'Content-Type': 'application/json'}) response = urllib.request.urlopen(request) except Exception as e: print(str(e))

我试过了,但帮不了我多少忙,同样的错误仍然存在,我不知道是什么导致了下面代码中的问题

try:
    request = urllib.request.Request(url,data=payload,method='PUT',headers={'Content-Type': 'application/json'})
    response = urllib.request.urlopen(request)
except Exception as e:
    print(str(e))
获取错误:-应为类型为“dict”的iterable数据指定内容长度

Python版本:3.4


我认为早在Python 3.2中就应该解决这个问题了。request不支持传入未编码的字典;如果要发送JSON数据,您需要自己将该字典编码为JSON:

import json

json_data = json.dumps(payload).encode('utf8')
request = urllib.request.Request(url, data=json_data, method='PUT',
                                 headers={'Content-Type': 'application/json'})
您可能想看看如何安装;通过使用
JSON
关键字参数,它支持对请求主体的JSON进行开箱即用编码:

import requests

response = requests.put(url, json=payload)
请注意,
内容类型
标题是为您自动设置的