Python 请求流示例在我的环境中不起作用
我一直在尝试使用Python请求使用Twitter流API 文档中有一个:Python 请求流示例在我的环境中不起作用,python,python-requests,twitter-streaming-api,Python,Python Requests,Twitter Streaming Api,我一直在尝试使用Python请求使用Twitter流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: # filte
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
属性包含连接打开时接收到的所有备份数据。)
本文档未提及导致请求.post在使用所有提供的数据之前返回所需的任何其他步骤。其他人似乎在使用类似的代码时没有遇到此问题,例如
我正在使用:
- Python 2.7
- Ubuntu 11.04
- 请求0.14.0
啊,我通过阅读代码找到了答案。在某个时刻,一个预取参数被添加到post方法(我假设还有其他方法)
我只需要添加一个
prefetch=False
kwarg到requests.post()
您需要关闭预取,我认为这是一个改变默认值的参数:
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开始,该参数已重命名,现在您使用:
进一步阅读表明,prefetch作为一个参数已经有一段时间了,但在版本0.13.6.:-)中,它的默认值更改为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)