Python 同时使用会话上下文管理器和stream=True
我想知道这个代码是否安全:Python 同时使用会话上下文管理器和stream=True,python,session,python-requests,Python,Session,Python Requests,我想知道这个代码是否安全: import requests with requests.Session() as s: response = s.get("http://google.com", stream=True) content = response.content 例如,像这样简单,这不会失败(注意我没有写“it works”:p),因为池不会立即关闭连接(这是会话/池的一个点,对吗?) 使用stream=True,响应对象应该具有其包含连接的raw属性,但我不确定该连接是否
import requests
with requests.Session() as s:
response = s.get("http://google.com", stream=True)
content = response.content
例如,像这样简单,这不会失败(注意我没有写“it works”:p),因为池不会立即关闭连接(这是会话/池的一个点,对吗?)
使用stream=True
,响应对象应该具有其包含连接的raw
属性,但我不确定该连接是否属于会话,然后如果在某个时候,如果我现在不阅读内容,但稍后,它可能已关闭
我目前的2美分是不安全的,但我不是100%确定
谢谢
[阅读请求代码后编辑]
在更详细地阅读了requests代码之后,似乎是requests.get
自己在做什么:
因为KWARG可能包含流
所以我猜答案是“它是安全的”好吧,我是通过挖掘
请求和urlib3
得到答案的
Response
对象拥有连接,直到显式调用close()
方法:
release\u conn()
是一种urlib3
方法,它释放连接并将其放回池中
def release_conn(self):
if not self._pool or not self._connection:
return
self._pool._put_conn(self._connection)
self._connection = None
如果会话
已被销毁(如将与
一起使用),则池已被销毁,连接无法恢复,并且刚刚关闭
TL;博士这是安全的
请注意,这也意味着在流
模式下,在响应明确关闭或内容完全读取之前,池的连接不可用。请参阅“正文内容工作流”。我在提问之前阅读了此链接,但这没有提及当时会话对象和流的行为。哦,我的糟糕!我在他们中间来回看了看,像个傻瓜一样错过了。这是一个好问题。祝你好运
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()
def release_conn(self):
if not self._pool or not self._connection:
return
self._pool._put_conn(self._connection)
self._connection = None