Python 请求字典作为表单数据

标签 python python-requests

我有一个 python 字典

x = {'id': 123, 'data': {'param1': 'hello', 'param2': 'world'}}

我正在尝试让我的表单数据成为

id=123
data[param1]=hello
data[param2]=world

不能将它作为 json 传递,因为接收它的 API 不接受 json 对象

我试过这样传递

requests​.post(url, data=x, headers={'content-type': 'application/x-www-form-urlencoded'})

请求发出时带有如下所示的表单数据

id=123
data=param1
data=param2

有办法解决这个问题吗?

最佳答案

您应该发布 data=x['data'] 而不是发布 data = x。这应该可以解决您的问题。

requests​.post(url, data=x['data'], headers={'content-type': 'application/x-www-form-urlencoded'})

或者更好的方法是从您的字典中删除 data 键并直接将字典创建为

x = {'param1': 'hello', 'param2': 'world'}

然后你可以这样发帖:

requests​.post(url, data=x['data'], headers={'content-type': 'application/x-www-form-urlencoded'})

选择最适合您的..

希望这有帮助:)

关于Python 请求字典作为表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436573/

相关文章:

python - 访问 token 刷新错误: invalid_grant from oauth2client

python - 通过python上传文件到imgur

python - 使用Python中的请求迭代向API发送请求

python - 为什么使用多线程求和是正确的?

python - 如何将不存在的类成员函数动态转换为现有的

python - 从我的 python 代码中进行 graphQL 突变,出现错误

python-requests - Google Cloud Run 上对外部 API 的调用被阻止

web-scraping - 如何在 BeautifulSoup 中只获取标签的内部文本,不包括嵌入的?

python - 在 Pandas 中如何在移动窗口的基础上计算 'Countif'?

python - 如何在 pandas 中按日期绘制数据并同时进行分组