问题描述
我想向实时流发出HTTPS请求,并保持连接处于打开状态,以便我可以继续从中读取内容并进行处理。
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想在python中编写脚本。我不确定如何在我的脚本中保持连接打开。我用curl测试了端点,使连接成功打开。但是我如何在Python中完成它。目前,我有以下代码:
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()
我从哪里开始?
谢谢!
推荐答案
看起来你的实时流是作为一个无休止的HTTP GET响应提供的,是吗?如果是这样,您可以使用python的内置。它会返回一个类似文件的对象,您可以从中读取所需内容,直到服务器挂起为止。
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.
f=urllib2.urlopen('https://encrypted.google.com/')
while True:
data = f.read(100)
print(data)
请记住,虽然urllib2说https,但它不验证服务器证书,所以你可能想尝试添加-on包如或以获得更好的安全性。 (我不确定urlgrabber是否支持https。)
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.)
这篇关于Python中的持久HTTPS连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!