user308827
user308827

Reputation: 21961

Closing python requests connection

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

In the above usage of python requests library, does the connection close automatically once requests.get is done running? If not, how can I make for certain that connection is closed

Upvotes: 7

Views: 9914

Answers (1)

idjaw
idjaw

Reputation: 26578

Yes, there is a call to a session.close behind the get code. If using a proper IDE like PyCharm for example, you can follow the get code to see what is happening. Inside get there is a call to request:

return request('get', url, params=params, **kwargs)

Within the definition of that request method, the call to session.close is made.

By following the link here to the requests repo, there is a call being made for the session control:

# 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)

Upvotes: 7

Related Questions