【问题标题】:Closing python requests connection关闭python请求连接
【发布时间】:2017-06-21 02:09:01
【问题描述】:
import requests
requests.get(path_url, timeout=100)

在上述python requests 库的使用中,requests.get 运行完成后连接是否会自动关闭?如果没有,我如何确定连接已关闭

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    是的,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)
    

    【讨论】:

    • 感谢@idjaw,如果我调用 requests.get(),您的回答是否也成立?
    • 是的。如答案中所述,get 调用调用request('get'...,如我的答案中以return 开头的行中指定的那样。如果您点击我提供的链接,您实际上还会在其中看到 get 方法以及它如何调用 request
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 2014-09-27
    • 2022-12-06
    • 2022-12-12
    • 2012-05-10
    相关资源
    最近更新 更多