python - 请求流示例在我的环境中不起作用

标签 python python-requests twitter-streaming-api

我一直在尝试使用 Python 请求来使用 Twitter Streaming API。

有一个 simple example在文档中:

import requests
import json

r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
    data={'track': 'requests'}, auth=('username', 'password'))

for line in r.iter_lines():
    if line: # filter out keep-alive new lines
        print json.loads(line)

当我执行它时,对 requests.post() 的调用永远不会返回。我已经试验并证明它肯定是连接到 Twitter 并从 API 接收数据。但是,它没有返回响应对象,而是坐在那里消耗与 Twitter 发送的数据一样多的数据。从上面的代码来看,我希望 requests.post() 返回一个与 Twitter 打开连接的响应对象,我可以继续接收实时结果。

(为了证明它正在接收数据,我在另一个 shell 中使用相同的凭据连接到 Twitter,于是 Twitter 关闭了第一个连接,调用返回了响应对象。r.content 属性包含连接打开时收到的所有备份数据。)

文档没有提及在消耗所有提供的数据之前导致 requests.post 返回所需的任何其他步骤。其他人似乎在使用类似的代码而没有遇到这个问题,例如here .

我正在使用:

  • python 2.7
  • Ubuntu 11.04
  • 请求 0.14.0

最佳答案

您需要关闭预取,我认为这是一个更改默认值的参数:

r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
    data={'track': 'requests'}, auth=('username', 'password'),
    prefetch=False)

for line in r.iter_lines():
    if line: # filter out keep-alive new lines
        print json.loads(line)

请注意,从 requests 1.x 开始,参数已重命名,现在您使用 stream=True :

r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
    data={'track': 'requests'}, auth=('username', 'password'),
    stream=True)

for line in r.iter_lines():
    if line: # filter out keep-alive new lines
        print json.loads(line)

关于python - 请求流示例在我的环境中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12301630/

相关文章:

java - 与远程服务 Stream API 连接

python - numpy.dot(a, b) 在具有相似维度的矩阵相乘时给出错误的结果

python - 计算图像上的水滴数量

python - Twitter.com 请求错误

python - 通过 Python 请求和 Postman 重新创建 XMLHttpRequest 的问题

java - 如何管理来自不同线程的不同 TwitterStream

python:转义XML中的非ascii字符

python - 为什么非常小的 checkinterval 不会减慢 python3 中 CPU 密集型多线程的速度?

python - 得到 200 响应而不是 302

javascript - 有没有办法在 twitter streaming api 过滤器上进行 AND 操作?