如何在python请求中发送列表GET [英] how to send a list in python requests GET

查看:100
本文介绍了如何在python请求中发送列表GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从服务器获取一些数据.我正在使用 python requests 库执行 GET:

I'm trying to GET some data from the server. I'm doing a GET with the python requests library:

my_list = #a list ['x', 'y', 'z']
payload = {'id_list': my_list}
requests.get(url, params=payload)

我的服务器接受一个网址:https://url.com/download?id_list

my server accepts a url: https://url.com/download?id_list

但是当我发送这个 get 请求时,我收到一个错误:

but when I send this get request, I get an error:

400 Bad Request

由于语法错误,服务器无法理解请求.<br/><br/>一个参数有多个值:
<pre>id_list</pre>

<h1>400 Bad Request</h1> The server cannot understand the request due to malformed syntax. <br /><br /> Got multiple values for a parameter:<br /> <pre>id_list</pre>

我看到了日志,请求是这样的:

I saw the log and the request looks like this:

url/download?id_list=x&id_list=y&id_list=z

我该如何解决这个问题?

how can I fix this?

推荐答案

好吧,实际上没有什么可以解决的,问题出在服务器端!requests 默认处理列表的方式就是它应该被处理的方式.

Well, there's actually nothing to fix, the issue being on the server side! The way requests handle list per default is the way it should be handled.

但您应该问的真正问题是服务器端的 API 期望什么?

But the real question you should be asking is what does the server side's API expect?

一旦你知道你可以使用requests来模仿它.

And once you know that you can mimic it using requests.

例如,服务器很可能需要一个 json 字符串作为 id_list 参数的参数.那么你可以这样做:

For example, it's likely to be that the server is expecting a json string as argument of the id_list parameter. Then you could do:

payload = {'id_list': json.dumps(my_list)}

但也有可能是服务器端需要一个逗号分隔的列表:

But it can be that the server side expects a comma separated list:

payload = {'id_list': ','.join(my_list)}

因此,您可以阅读尝试与之通信的 API 的文档(或自行修改).

So it's up to you to read the documentation (or hack your way around) of the API you try to communicate with.

注意:正如@bob_dylan 建议您可以尝试使用 requests.get(url, json=payload) 但事实上,json 有效负载通常用于 POST 查询中,很少使用在 GET 中.

N.B.: as @bob_dylan suggests you can try with requests.get(url, json=payload) but afaict, json payloads are usually used in POST queries, rarely in GETs.

这篇关于如何在python请求中发送列表GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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