如何在python请求中使用相同的键发布多个值? [英] how to post multiple value with same key in python requests?

查看:20
本文介绍了如何在python请求中使用相同的键发布多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

requests.post(url, data={'interests':'football','interests':'basketball'})

我试过这个,但它不起作用.我如何在 interests 字段中发布 footballbasketball ?

解决方案

字典键必须唯一,不能重复.您可以改用一系列键值元组,并将其传递给 data:

requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])

或者,将data字典的值lists;列表中的每个值都用作单独的参数条目:

requests.post(url, data={'interests': ['football', 'basketball']})

演示 POST 到 http://httpbin.org:

<预><代码>>>>进口请求>>>url = 'http://httpbin.org/post'>>>r = requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])>>>请求体'兴趣=足球&兴趣=篮球'>>>r.json()['表单']{u'interests': [u'football', u'basketball']}>>>r = requests.post(url, data={'interests': ['football', 'basketball']})>>>请求体'兴趣=足球&兴趣=篮球'>>>r.json()['表单']{u'interests': [u'football', u'basketball']}

requests.post(url, data={'interests':'football','interests':'basketball'})

I tried this, but it is not working. How would I post football and basketball in the interests field?

解决方案

Dictionary keys must be unique, you can't repeat them. You'd use a sequence of key-value tuples instead, and pass this to data:

requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])

Alternatively, make the values of the data dictionary lists; each value in the list is used as a separate parameter entry:

requests.post(url, data={'interests': ['football', 'basketball']})

Demo POST to http://httpbin.org:

>>> import requests
>>> url = 'http://httpbin.org/post'
>>> r = requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])
>>> r.request.body
'interests=football&interests=basketball'
>>> r.json()['form']
{u'interests': [u'football', u'basketball']}
>>> r = requests.post(url, data={'interests': ['football', 'basketball']})
>>> r.request.body
'interests=football&interests=basketball'
>>> r.json()['form']
{u'interests': [u'football', u'basketball']}

这篇关于如何在python请求中使用相同的键发布多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆