pythonhttpurllib2httplibpython-requests

Python-Requests close http connection


I was wondering, how do you close a connection with Requests (python-requests.org)?

With httplib it's HTTPConnection.close(), but how do I do the same with Requests?

Code:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
for line in r.iter_lines():
    if line:
        self.mongo['db'].tweets.insert(json.loads(line))

Solution

  • As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.

    The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.

    s = requests.session()
    s.config['keep_alive'] = False