【发布时间】:2017-06-21 02:09:01
【问题描述】:
import requests
requests.get(path_url, timeout=100)
在上述python requests 库的使用中,requests.get 运行完成后连接是否会自动关闭?如果没有,我如何确定连接已关闭
【问题讨论】:
import requests
requests.get(path_url, timeout=100)
在上述python requests 库的使用中,requests.get 运行完成后连接是否会自动关闭?如果没有,我如何确定连接已关闭
【问题讨论】:
是的,get 代码后面有一个对 session.close 的调用。例如,如果使用像 PyCharm 这样的适当 IDE,您可以按照 get 代码查看发生了什么。在get 内部有一个请求调用:
return request('get', url, params=params, **kwargs)
在 request 方法的定义中,调用了 session.close。
通过链接here 到请求存储库,正在调用会话控制:
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
【讨论】:
get 调用调用request('get'...,如我的答案中以return 开头的行中指定的那样。如果您点击我提供的链接,您实际上还会在其中看到 get 方法以及它如何调用 request。