首页 > 解决方案 > 处理 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方法引发的错误

标签: pythontwittererror-handlingtweepytwitter-streaming-api

解决方案


我想补充一下@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

推荐阅读