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

Gar*_*eth 5 python python-requests twitter-streaming-api

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

文档中有一个简单的例子:

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)
Run Code Online (Sandbox Code Playgroud)

执行此操作时,调用requests.post()永不返回.我已经进行了实验并证明它肯定会连接到Twitter并从API接收数据.但是,它不是返回响应对象,而是在那里消耗尽可能多的数据,就像Twitter发送的一样多.从上面的代码判断,我希望requests.post()返回一个与Twitter打开连接的响应对象,我可以继续接收实时结果.

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

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

我正在使用:

  • Python 2.7
  • Ubuntu 11.04
  • 请求0.14.0

Mar*_*ers 10

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

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)
Run Code Online (Sandbox Code Playgroud)

更新:在最新的requests框架中,使用stream而不是prefetch:

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)
Run Code Online (Sandbox Code Playgroud)


Gar*_*eth 5

啊,我通过阅读代码找到了答案.在某些时候,pre方法参数被添加到post方法(和我假设的其他方法).

我只需要添加一个prefetch=Falsekwarg requests.post().