Python 中的持久 HTTPS 连接
我想向实时流发出 HTTPS 请求并保持连接打开,以便我可以继续从中读取内容并进行处理。
我想用 python 编写脚本。我不确定如何在我的脚本中保持连接打开。我已经使用curl 测试了端点,它使连接成功保持打开状态。但我该如何在Python中做到这一点。目前,我有以下代码:
c = httplib.HTTPSConnection('userstream.twitter.com')
c.request("GET", "/2/user.json?" + req.to_postdata())
response = c.getresponse()
我从这里去哪里?
谢谢!
I want to make an HTTPS request to a real-time stream and keep the connection open so that I can keep reading content from it and processing it.
I want to write the script in python. I am unsure how to keep the connection open in my script. I have tested the endpoint with curl which keeps the connection open successfully. But how do I do it in Python. Currently, I have the following code:
c = httplib.HTTPSConnection('userstream.twitter.com')
c.request("GET", "/2/user.json?" + req.to_postdata())
response = c.getresponse()
Where do I go from here?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您的实时流是作为一个无休止的 HTTP GET 响应来传递的,是吗?如果是这样,你可以使用 python 的内置 urllib2.urlopen() 。它返回一个类似文件的对象,您可以从中读取任意数量的数据,直到服务器挂断为止。
请记住,虽然 urllib2 使用 https,但它不会验证服务器证书,因此您可能需要尝试添加像 pycurl 或 urlgrabber 以获得更好的安全性。 (我不确定 urlgrabber 是否支持 https。)
It looks like your real-time stream is delivered as one endless HTTP GET response, yes? If so, you could just use python's built-in urllib2.urlopen(). It returns a file-like object, from which you can read as much as you want until the server hangs up on you.
Keep in mind that although urllib2 speaks https, it doesn't validate server certificates, so you might want to try and add-on package like pycurl or urlgrabber for better security. (I'm not sure if urlgrabber supports https.)
连接保持活动功能在任何 https 的 python 标准库中都不可用。最成熟的选项可能是
urllib3
Connection keep-alive features are not available in any of the python standard libraries for https. The most mature option is probably
urllib3
httplib2 支持此功能。 (我认为这是最成熟的选择,还不知道 urllib3,所以 TokenMacGuy 可能仍然是对的)
编辑:虽然 httplib2 确实支持持久连接,但我不认为你可以真正使用它来消费流(即。一个长响应与同一连接上的多个请求),我现在意识到您可能需要它。
httplib2 supports this. (I'd have thought this the most mature option, didn't know urllib3 yet, so TokenMacGuy may still be right)
EDIT: while httplib2 does support persistent connections, I don't think you can really consume streams with it (ie. one long response vs. multiple requests over the same connection), which I now realise you may need.