Skip to content

Instantly share code, notes, and snippets.

@akaIDIOT
Last active March 25, 2016 14:55
Show Gist options
  • Save akaIDIOT/ab937951c34fdfd8f6d3 to your computer and use it in GitHub Desktop.
Save akaIDIOT/ab937951c34fdfd8f6d3 to your computer and use it in GitHub Desktop.
Context manager to drain content from a requests.Response object in the case its content is not fully read
class drain(object):
"""
Context manager to make sure a `Response` object is drained of content.
Can be used to return a connection used to retrieve a response back to the
connection pool it came from in case the actual response content of the
response is not needed, e.g.:
.. code-block:: python
response = session.get('https://example.com/')
with drain(response):
# we're only interested in the status code here and ignore the
# response content, drain will make sure the content is consumed
# and the underlying connection can be reused
return response.status_code == 200
"""
def __init__(self, response):
"""
Creates a new draining context manager for *response*.
:param response: the `Response` to drain on exit
"""
self.response = response
def __enter__(self):
return self.response
def __exit__(self, exc_type, exc_val, exc_tb):
# accessing response.content will make sure it is drained
self.response.content
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment