我正在使用Python和Requests从Twitter's streaming API请求数据。我想用一组参数请求数据,一段时间后,用一组新参数更改请求。
在下面简单的工作示例中,我向Twitter流媒体API索取关键字' python。'一小时后,我会向API询问关键字' ruby。'但是,要做到这一点,我正在创建一个新的请求对象;我没有改变原始物体。
import requests
import json
import time
USER = 'user'
PW = 'pw'
def make_request(keyword):
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'track': keyword}, auth=(USER,PW))
for line in r.iter_lines():
if line:
print json.loads(line)
if time.time() > start_of_last_request + 3600:
break
count = 0
keywords = ['python', 'ruby']
while count < 2:
start_of_last_request = time.time()
make_request(keywords[count])
count = count + 1
最终,我需要每小时创建一个新查询,我担心我会创建太多连接。
我的问题是:是否有更好的方法将请求更改为Twitter API?我实际上是在创建多个连接吗?如果是这样,我该如何避免这种情况? (有关如何close the previous connections的建议,但解决方案对我来说并不合适。)
我将不胜感激任何帮助。谢谢!
答案 0 :(得分:1)
在您关联时,为了在完成请求后关闭连接,请将keep-alive
值设置为False
,而不是默认True
:
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'track': keyword}, auth=(USER,PW),
config={'keep_alive':False})
这将确保在您完成连接后关闭连接。