如何使用{单键:多值}创建HTTP请求数据 [英] How to create HTTP-request data with {single key:multi values}

查看:160
本文介绍了如何使用{单键:多值}创建HTTP请求数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要发送 HTTP POST请求,其数据如下:

I need to send HTTP POST request with data as follow:

data = {'id[]': '1', 'id[]': '2', 'id[]': '3'}

值列表实际上是未知的,但让它成为 values_list = ['1','2','3']

当然如果尝试

for value in values_list:
    data["id[]"] = value

我得到 {'id []':'3'} 作为键值对将被覆盖在每次迭代...

I get {'id[]': '3'} as key-value pair will be overwritten on each iteration...

我使用了这个解决方案:

data = {}

class data_keys(object):
    def __init__(self, data_key):
        self.data_key = data_key

for value in values_list:
    data[data_keys('id[]')] = value

但是我的数据看起来像

{<__main__.data_keys object at 0x0000000004BAE518>: '2',
 <__main__.data_keys object at 0x0000000004BAED30>: '1',
 <__main__.data_keys object at 0x0000000004B9C748>: '3'}

我的代码有什么问题?我还可以用单键创建dict吗?

What is wrong with my code? How else can I simply create dict with single key?

更新

这样我的 code>请求看起来像:

This how my HTTP request looks like:

requests.post(url, data={"id[]": '1', "id[]": '2', "id[]": '3'}, auth=HTTPBasicAuth(user_name, user_passw))

标题更新

推荐答案

虽然你可以键以允许看似相等的键,这可能不是一个好主意,因为这依赖于关键字如何转换为字符串的实现细节。另外,如果你需要调试这种情况,肯定会造成混乱。

While you can hack dictionary keys in order to allow seemingly "equal" keys, this is probably not a good idea, as this relies on the implementation detail on how the key is transformed into a string. Furthermore, it will definitely cause confusion if you ever need to debug this situation.

一个更容易和支持的解决方案实际上是内置在表单数据编码机制:您只需传递一个值列表:

A much easier and supported solution is actually built into the form data encode mechanism: You can simply pass a list of values:

data = {
    'id[]': ['1', '2', '3']
}

req = requests.get(url='http://www.example.com', params=data)
print(req.url) # 'http://www.example.com/?id%5B%5D=1&id%5B%5D=2&id%5B%5D=3'

所以你可以直接将你的 values_list 直接传递到字典中,一切都可以正常工作,而无需任何东西。

So you can just pass your values_list directly into the dictionary and everything will work properly without having to hack anything.

如果你发现自己处于一种你认为这样的字典不起作用的情况,你还可以提供一个可迭代的两元组(第一个值是关键,第二个值是第二个值):

And if you find yourself in a situation where you think such a dictionary does not work, you can also supply an iterable of two-tuples (first value being the key, second the value):

data = [
    ('id[]', '1'),
    ('id[]', '2'),
    ('id[]', '3')
]

req = requests.get(url='http://www.example.com', params=data)
print(req.url) # 'http://www.example.com/?id%5B%5D=1&id%5B%5D=2&id%5B%5D=3'

这篇关于如何使用{单键:多值}创建HTTP请求数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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