python - 处理 Tweepy api 返回的 420 响应码
问题描述
每当用户登录我的应用程序并进行搜索时,我都必须启动一个流式 API 来获取他所需的数据。
这是我的流 API 类
import tweepy
import json
import sys
class TweetListener(tweepy.StreamListener):
def on_connect(self):
# Called initially to connect to the Streaming API
print("You are now connected to the streaming API.")
def on_error(self, status_code):
# On error - if an error occurs, display the error / status code
print('An Error has occured: ' + repr(status_code))
return False
def on_data(self, data):
json_data = json.loads(data)
print(json_data)
这是我的 python 代码文件,它调用上面的类来启动 Twitter 流
import tweepy
from APIs.StreamKafkaApi1 import TweetListener
consumer_key = "***********"
consumer_secret = "*********"
access_token = "***********"
access_secret = "********"
hashtags = ["#ipl"]
def callStream():
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)
tweetListener = TweetListener(userid,projectid)
streamer = tweepy.Stream(api.auth, tweetListener)
streamer.filter(track=hashtags, async=True)
if __name__ == "__main__":
callStream()
但是,如果我点击两次以上,我的应用程序将返回错误代码 420。我想在发生错误 420 时更改用于获取数据的 API(使用多个键) 。
如何在def callStream()中获取 TweetListener类的on_error方法引发的错误
解决方案
我想补充一下@Andy Piper 的答案。响应 420 表示您的脚本发出了太多请求并且已受到速率限制。为了解决这个问题,这是我所做的(在 TweetListener 类中):
def on_limit(self,status):
print ("Rate Limit Exceeded, Sleep for 15 Mins")
time.sleep(15 * 60)
return True
这样做,错误将被处理。
如果您坚持使用多个键。我不确定,但尝试对 TweetListener 和流媒体进行异常处理,对于 tweepy.error.RateLimitError 并使用下一个 API 密钥对函数进行递归调用?
def callStream(key):
#authenticate the API keys here
try:
tweetListener = TweetListener(userid,projectid)
streamer = tweepy.Stream(api.auth, tweetListener)
streamer.filter(track=hashtags, async=True)
except tweepy.TweepError as e:
if e.reason[0]['code'] == "420":
callStream(nextKey)
return True
推荐阅读
- python - 将字典附加到 json 响应
- excel - 删除大型 Microsoft excel 数据表中的第 6 行第 7 行
- r - 字符串在 R 中拆分为一列,反向地理代码为 lat long
- android - 应用程序没有响应,为什么不显示 ANR 弹出窗口?
- javascript - 在javascript中每4个计数后创建新的父div和4个子div
- wpf - 将设置的窗口样式应用于窗口
- linkedin - LinkedIn API:adCampaignsV2 的突然权限错误
- amazon-ec2 - 地理服务器 NGINX 配置
- nestjs - Using Nestjs to poll on DB Changes
- java - Floating action Button visibility issue?