Python 请求 - 发送 null 作为查询参数值

标签 python python-requests query-string

我的 URL 可以将 null 作为查询参数的值,如下所示:

https:/api.server.com/v1/users/?parent=null

当我尝试使用 Requests 在 Python 中发送请求时,我传递了 None:

requests.get(
    BASE_URL + USER_URL,
    headers = get_headers(),
    timeout = 60,
    params = {
        'parent': None
    }
)

但是,如果它设置为 None,它似乎会跳过查询参数 parent。我该如何强制执行?

最佳答案

您不能使用 resquests 包传递 null 值,因为它是文档中所述的默认行为:

Note that any dictionary key whose value is None will not be added to the URL’s query string.

一些解决方案:

  1. 也许您可以假设后端没有它是 null,或者;
  2. 您可以传递一个空字符串,或者;
  3. 传递一个不存在的 ID,例如 0/-1,或者;
  4. 传递 bool 参数,例如 parent=falseno-parent=true
  5. 我不建议传递字符串 'null',因为根据您使用的后端框架,它可能会有不同的解释。但如果是这种情况,您可以这样做。

关于Python 请求 - 发送 null 作为查询参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67344438/

相关文章:

python - 值错误: The truth value of a Series is ambiguous in one hot encoding error

Python Threading.Timer正在调用命令而无需等待

python - 通过 Python 的单个连接进行多个请求

python-3.x - 如何用 python 中 null 之前的所有前值和 null 之后的第一个后续值的平均值填充空值?

rust - 如何解码 URL 并将查询字符串作为 HashMap?

python - 分割字符串时丢失编码

Python 3.2,Pygame "AttributeError: ' pygame.Rect'对象没有属性 'bullet_RECT'

python:如何将 'unicodedata' 模块添加到我当前的 python 库

query-string - 虚拟 url 中的 urlrewritING.net 查询字符导致重定向循环

regex - .htaccess 中的 CodeIgniter 查询字符串重写