Python 请求关闭 http 连接 [英] Python-Requests close http connection

查看:84
本文介绍了Python 请求关闭 http 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,您如何关闭与 Requests (python-requests.org) 的连接?

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

使用 httplibHTTPConnection.close(),但是我如何对请求做同样的事情?

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

代码:

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

推荐答案

如前所述 这里,真的没有像 HTTP 连接这样的东西,httplib 所指的 HTTPConnection 实际上是底层 TCP 连接,它并不真正了解您的要求.请求将其抽象化,您将永远看不到它.

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.

最新版本的 Requests 实际上会在您发出请求后保持 TCP 连接处于活动状态.如果您确实希望关闭 TCP 连接,您可以将请求配置为不使用 保持活动.

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

这篇关于Python 请求关闭 http 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆