问题描述
似乎当 data
中的键的值为 None
时,请求中不包含该键.
为什么会这样?我期待一个空字符串,或者类似 json.dumps(d)
的东西,其中 None
被呈现为 null
.我相信有一个很好的理由——只是好奇它是什么.(我能想到的一件事是,可能没有可用于 POST 请求的 null
或 None
编码——这是真的吗?)
另外一个好奇——为什么 requests
会默默地忽略这些数据而不是抛出错误?
将字典元素设置为 None
是您明确表示不希望将该参数发送到服务器的方式.
我在 requests.Request()
文档中找不到具体提到的这一点,但在 在 URL 中传递参数 它说:
请注意,任何值为 None 的字典键都不会添加到 URL 的查询字符串中.
显然它也对 POST
请求使用一致的逻辑.
如果要发送空字符串,请将字典元素设置为空字符串而不是None
.
It seems that when a key in data
has a value of None
, the key isn't included by requests.
>>> req = requests.Request('POST', 'http://google.com', data=dict(a=None, b=1))
>>> req.prepare().body
'b=1'
Why is this the case? I was expecting an empty string, or something like json.dumps(d)
where None
is rendered as null
. I'm sure there's a good reason -- just curious about what it is. (One thing I can think of is that maybe there just isn't an encoding of null
or None
available to the POST request -- is that true?)
Additionally curious -- why does requests
silently ignore such data instead of throwing an error?
Setting a dictionary element to None
is how you explicitly say that you don't want that parameter to be sent to the server.
I can't find this mentioned specifically in the requests.Request()
documentation, but in Passing Parameters in URLs it says:
Obviously it uses consistent logic for POST
requests as well.
If you want to send an empty string, set the dictionary element to an empty string rather than None
.
这篇关于为什么我不能使用 Python 的 `requests` 库在 POST 请求中将 `None` 作为数据发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!