关闭python请求连接

时间:2017-06-21 02:09:01

标签: python python-requests

import requests
requests.get(path_url, timeout=100)

在python请求库的上述用法中,一旦request.get运行完毕,连接是否会自动关闭?如果没有,我如何确定连接已关闭

1 个答案:

答案 0 :(得分:5)

是的,session.close代码后面有一个get。例如,如果使用像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)