攤檔的東西可以預料的,你必須考慮他們(和其他類型的連接錯誤)在你的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
閱讀文檔[https://dev.twitter.com/streaming/overview/connecting )。有關於*攤位*的部分。這應該給你關於你正在經歷的信息。查找異常將導致多個鏈接提供有關該異常的信息,從而爲發生這種情況提供背景信息。 – idjaw
@idjaw好的,謝謝讓我檢查他們 –