简体   繁体   English

在Python的Twython中适应Twitter的速率限制

[英]Accommodating Twitter's rate limit in Python's Twython

I'm pulling data through Twitter's REST API using Twython. 我正在使用Twython通过Twitter的REST API提取数据。 I want the code to automatically rest as long as it needs to when it's reached the Twitter rate limit, then begin querying again. 我希望代码在达到Twitter速率限制时会根据需要自动休息,然后再次开始查询。

Here's the code, which takes a list of Twitter IDs and adds their followers'IDs to the list: 这是代码,其中包含Twitter ID列表,并将其关注者ID添加到列表中:

for user in first_ids:
    try:
        followers = twitter.get_followers_ids(user_id=user, count=600)
        for individual in followers['ids']:    
            if individual not in ids:
                ids.append(individual)
    except TwythonRateLimitError as error:
        remainder = float(twitter.get_lastfunction_header(header='x-rate-limit-reset')) - time.time()
        time.sleep(remainder)
        continue

When I run it I get the following error: "Connection aborted. Error 10054: An existing connection was forcibly closed by the remote host" 运行它时,出现以下错误:“连接异常终止。错误10054:远程主机强行关闭了现有连接”

What does the error mean? 错误是什么意思? I imagine it's related to Twitter's rate limit -- is there another way around it? 我想这与Twitter的速率限制有关-是否还有其他方法可以解决?

you're leaving the connection open while your program sleeps, try closing it manually and then connecting again after the sleep timeout. 您在程序进入睡眠状态时保持连接打开状态,请尝试手动将其关闭,然后在睡眠超时后重新连接。 Something like: 就像是:

    except TwythonRateLimitError as error:
        remainder = float(twitter.get_lastfunction_header(header='x-rate-limit-reset')) - time.time()
        twitter.disconnect()
        time.sleep(remainder)
        twitter = Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        continue

if you are using REST api you can use the same solution deleting the api instead of using .disconnect() simply use 如果您使用的是REST API,则可以使用相同的解决方案删除该API,而不是使用.disconnect(),只需使用

del twitter

instead of 代替

twitter.disconnect()

i had the same problem and it worked for me 我有同样的问题,对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM