Python 中的持久 HTTPS 连接

发布于 2024-12-01 06:20:23 字数 343 浏览 6 评论 0原文

我想向实时流发出 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月依秋水 2024-12-08 06:20:23

看起来您的实时流是作为一个无休止的 HTTP GET 响应来传递的,是吗?如果是这样,你可以使用 python 的内置 urllib2.urlopen() 。它返回一个类似文件的对象,您可以从中读取任意数量的数据,直到服务器挂断为止。

f=urllib2.urlopen('https://encrypted.google.com/')
while True:
    data = f.read(100)
    print(data)

请记住,虽然 urllib2 使用 https,但它不会验证服务器证书,因此您可能需要尝试添加像 pycurlurlgrabber 以获得更好的安全性。 (我不确定 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.

f=urllib2.urlopen('https://encrypted.google.com/')
while True:
    data = f.read(100)
    print(data)

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

温柔嚣张 2024-12-08 06:20:23

连接保持活动功能在任何 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

独自唱情﹋歌 2024-12-08 06:20:23

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文