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

问题描述 投票:5回答:2

我一直在尝试使用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的开放连接,我可以继续接收实时结果。

“连接已打开。)

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

我正在使用:

    Python 2.7
  • Ubuntu 11.04
  • 请求0.14.0
python python-requests twitter-streaming-api
2个回答
10
投票
您需要关闭预取,我认为这是更改默认值的参数:

here

注意,自请求1.x起,该参数已重命名,现在您使用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)

stream=True


5
投票
啊,我通过阅读代码找到了答案。在某个时候,预取参数已添加到post方法(我认为还有其他方法)中。

我只需要在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) kwarg。

© www.soinside.com 2019 - 2024. All rights reserved.