我一直在尝试使用 Python 请求来使用 Twitter Streaming API。
有一个简单的例子 http://docs.python-requests.org/en/latest/user/advanced/#streaming-requests在文档中:
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 http://kracekumar.com/post/19556427690/n00bs-epic-research-on-twitters-streaming-api-on.
我在用着:
- Python 2.7
- 乌班图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 https://requests.readthedocs.io/en/master/user/advanced/#body-content-workflow:
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)