在无服务器功能中重用 Python 请求 session - when/how 这个 session 应该关闭吗?

Reusing Python requests session in serverless function - when/how this session should be closed?

我有一个无服务器函数 运行 Python 3.9(技术上是 Azure 上的 Function App,但我会参考 GCP Cloud Function,因为我找到了更好的文档)。

我的无服务器函数经常使用 requests.put。 我想为请求添加重试机制,因此我可以将 requests.Session() 与一些自定义 HTTPAdapter 一起使用。如果我重用这个 session 我会有一个重试机制,我会压缩一些性能。

所以基本上我想保持持久连接而不是在每次调用函数时都创建一个新连接,我得到了this documentation of GCP Maintaining Persistent Connections

附带的代码片段是:

import requests

# Create a global HTTP session (which provides connection pooling)
session = requests.Session()


def connection_pooling(request):
    """
    HTTP Cloud Function that uses a connection pool to make HTTP requests.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """

    # The URL to send the request to
    url = 'http://example.com'

    # Process the request
    response = session.get(url)
    response.raise_for_status()
    return 'Success!'

我的问题是 - 这个session何时以及如何关闭? session 是一个上下文管理器,我原以为它会被关闭。

一旦您的函数实例 自身 被关闭,GCP Cloud Functions 将自动清理 session 对象。

(持久连接的要点是在对特定功能实例的多个顺序请求中维护它们。)

怀疑 Azure Functions 很相似,但不要引用我的话。