Twitter Api Python Connection失误了

时间:2017-06-16 11:58:52

标签: python twitter

我正在使用TwitterAPI python库并在获取数据时发出此错误

File "/Users/danny/.venv/versions/2.7.9/lib/python2.7/site-packages/TwitterAPI/TwitterAPI.py", line 263, in _iter_stream
    raise TwitterConnectionError('Twitter stream stalled')
TwitterConnectionError: Twitter stream stalled

我正在使用python 2.7

1 个答案:

答案 0 :(得分:0)

停顿是可以预期的,您必须在Twitter客户端中考虑它们(以及其他类型的连接错误)。 TwitterAPI库确实检查了档位。当它们发生时,抛出TwitterConnectionError。这是一个信号,您只需重试您的请求即可。你不需要设置一个90秒的计时器。这是由TwitterAPI为您完成的。为了获得真正健壮的代码,您还应该处理TwitterRequestError。这是一个处理这两个例外的模板,以保持代码运行并保持在Twitter的指导原则中:

from TwitterAPI import TwitterAPI
api = TwitterAPI(CONSUMER_KEY,
                 CONSUMER_SECRET,
                 ACCESS_TOKEN_KEY,
                 ACCESS_TOKEN_SECRET)

while True:
    try:
        iterator = api.request('statuses/filter', {'track':'pizza'}).get_iterator()
        for item in iterator:
            if 'text' in item:
                print(item['text'])
            elif 'disconnect' in item:
                event = item['disconnect']
                if event['code'] in [2,5,6,7]:
                    # something needs to be fixed before re-connecting
                    raise Exception(event['reason'])
                else:
                    # temporary interruption, retry request
                    break
    except TwitterRequestError as e:
        if e.status_code < 500:
            # something needs to be fixed before re-connecting
            raise
        else:
            # temporary interruption, retry request
            pass
    except TwitterConnectionError:
        # temporary interruption, retry request
        pass