【问题标题】:Using session context manager and stream=True at the same time同时使用会话上下文管理器和 stream=True
【发布时间】:2017-12-09 02:47:50
【问题描述】:

我想知道这段代码是否安全:

import requests
with requests.Session() as s:
    response = s.get("http://google.com", stream=True)
content = response.content

例如像这样简单,这不会失败(注意我没有写“它有效”:p),因为池无论如何都不会立即关闭连接(这是会话/池的一个点,对吗?) .

使用stream=True,响应对象应该具有包含连接的raw 属性,但我不确定连接是否由会话拥有,然后如果我不拥有'现在不阅读内容,但稍后可能已关闭。

我目前的 2 美分是不安全的,但我不是 100% 确定。

谢谢!

[阅读请求代码后编辑]

在详细阅读了请求代码后,似乎requests.get 正在做自己的事情:

https://github.com/requests/requests/blob/master/requests/api.py

def request(method, url, **kwargs):
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)

因为 kwargs 可能包含 stream

所以我猜答案是“它很安全”。

【问题讨论】:

  • docs.python-requests.org/en/master/user/advanced 参见“正文内容工作流程”
  • 我在提问之前阅读了这个链接,这并没有提到当时 Session 对象和流的行为。
  • 哦,我的错!我在他们之间来回看了看,像个傻瓜一样错过了。这是一个很好的问题。祝你好运。

标签: python session python-requests


【解决方案1】:

好的,我通过挖掘 requestsurllib3 得到了答案

Response 对象拥有连接,直到显式调用 close() 方法:

https://github.com/requests/requests/blob/24092b11d74af0a766d9cc616622f38adb0044b9/requests/models.py#L937-L948

def close(self):
    """Releases the connection back to the pool. Once this method has been
    called the underlying ``raw`` object must not be accessed again.
    *Note: Should not normally need to be called explicitly.*
    """
    if not self._content_consumed:
        self.raw.close()

    release_conn = getattr(self.raw, 'release_conn', None)
    if release_conn is not None:
        release_conn()

release_conn() 是一个urllib3 方法,这会释放连接并将其放回池中

def release_conn(self):
    if not self._pool or not self._connection:
        return

    self._pool._put_conn(self._connection)
    self._connection = None

如果Session 被破坏(如使用with),池被破坏,连接无法恢复,它只是关闭。

TL;DR;这是安全的。

请注意,这也意味着在stream 模式下,在显式关闭响应或完全读取内容之前,连接对池不可用。

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多