如何判断 requests.Session() 是否良好?

ca9*_*3d9 0 python session python-requests

我有以下与会话相关的代码,必须连续运行。

代码

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
Run Code Online (Sandbox Code Playgroud)

注意:我将线路移出http = requests.Session()了循环。

问题

如何检查会话是否正常工作

不工作会话的一个示例可能是在 Web 服务器重新启动之后。或者负载均衡器重定向到不同的 Web 服务器。

hc_*_*dev 5

requests.Session对象只是一个持久性和连接池对象,允许客户端的不同 HTTP 请求之间共享状态。

如果服务器意外关闭会话,从而使其无效,服务器可能会响应一些指示错误的 HTTP 状态代码。

因此请求会引发错误。请参阅错误和异常

Requests 显式引发的所有异常都继承自requests.exceptions.RequestException.

请参阅的扩展类RequestException

方法1:使用实现打开/关闭try/except

您的代码可以在 try/ except 块中捕获此类异常。这取决于服务器的 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
Run Code Online (Sandbox Code Playgroud)

根据您的案例的服务器响应,实施方法session_was_closed(exception)

方法2:使用自动打开/关闭with

高级用法来看,会话对象

会话也可以用作上下文管理器:

with requests.Session() as s:
    s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
Run Code Online (Sandbox Code Playgroud)

这将确保退出 with 块后会话立即关闭,即使发生未处理的异常也是如此。