【发布时间】:2015-07-07 16:00:54
【问题描述】:
import requests
while True:
try:
posting = requests.post(url,json = data,headers,timeout = 3.05)
except requests.exceptions.ConnectionError as e:
continue
# If a read_timeout error occurs, start from the beginning of the loop
except requests.exceptions.ReadTimeout as e:
continue
更多代码的链接:Multiple accidental POST requests in Python
此代码使用 requests 库无限期地执行 POST 请求。我注意到当尝试多次失败并且while循环多次启动时,当我最终可以发送发布请求时,我会在同一秒内从服务器端找到多个条目。我正在同时写入一个 txt 文件,它只显示一个条目。每个条目是 5 个读数。这是图书馆本身的问题吗?有没有办法来解决这个问题?!无论我提出什么样的条件,它仍然不起作用:/!
You can notice the reading at 12:11:13 has 6 parameters per second while at 12:14:30 (after the delay, it should be every 10 seconds) it is a few entries at the same second!!! 3 entries that make up 18 readings in one second, instead of 6 only!
【问题讨论】:
-
这里的预期功能是什么?
-
该代码应该发送一个 GET 请求,然后 POST 并重复。有时由于网络问题,POST 请求失败了几次,所以我重复 2 次,如果已发布,否则 GET 并尝试再次发布。有时当尝试 POST 但失败时,经过几次尝试,它最终会 POST 但爆出一组条目而不是一个条目。如图所示。图为服务器端。
-
我认为我们需要更多代码。另外,请修正你的缩进——它们在 Python 中很重要!最后,您能再看看
.post方法中的参数吗?他们很混乱。 -
我认为
while True:之后的所有内容都应该缩进另一个级别。在 Python 中,您必须在关键字参数(如json = data和timeout = 3.05)之前有所有非关键字参数(如url和headers)。但我实际上假设你的意思是.post(url, data=json, headers=headers, timeout=3.05)。无论如何,你的代码肯定不会像问题中写的那样运行。 -
不,坚持
json=data,我只是把它翻过来了。
标签: python python-requests try-except