我有以下与会话相关的代码,必须连续运行。
代码
import requests
http = requests.Session()
while True:
# if http is not good, then run http = requests.Session() again
response = http.get(....)
# process respons
# wait for 5 seconds注意:我将行http = requests.Session()移出循环。
问题
如何检查会话是否有效
不工作会话的一个示例可能是在重新启动web服务器之后。或者负载平衡器重定向到另一个web服务器。
发布于 2022-05-19 23:13:39
requests.Session对象只是一个持久化和连接池对象,以允许客户端不同HTTP请求之间的共享状态。
如果服务器意外地关闭了一个会话,使它变得无效,服务器可能会用一些错误指示的HTTP状态代码进行响应。
因此,请求将引发错误。请参阅错误和例外
所有请求显式引发的异常都继承自
requests.exceptions.RequestException。
方法1:使用try/except实现开放/关闭
您的代码可以在try/ can块中捕获这样的异常。这取决于服务器的API接口规范,它将如何发出无效/关闭会话的信号。这个信号响应应该在except块中进行评估。
在这里,我们使用session_was_closed(exception)函数计算异常/响应,使用Session.close()在打开新会话之前正确地关闭会话。
import requests
# initially open a session object
s = requests.Session()
# execute requests continuously
while True:
try:
response = s.get(....)
# process response
except requests.exceptions.RequestException as e:
if session_was_closed(e):
s.close() # close the session
s = requests.Session() # opens a new session
else:
# process non-session-related errors
# wait for 5 seconds根据情况的服务器响应,实现方法session_was_closed(exception)。
方法2:使用with自动打开/关闭
会话还可以用作上下文管理器: 使用requests.Session() as : s.get('https://httpbin.org/cookies/set/sessioncookie/123456789') 这将确保会话在with块退出后立即关闭,即使发生了未处理的异常。
发布于 2022-05-19 22:08:24
我会翻转逻辑,添加一次尝试--除了。
import requests
http = requests.Session()
while True:
try:
response = http.get(....)
except requests.ConnectionException:
http = requests.Session()
continue
# process respons
# wait for 5 seconds 有关更多信息,请参见这个答案。我没有测试引发的异常是否是那个异常,所以请测试它。
https://stackoverflow.com/questions/72311444
复制相似问题