如何在请求中优雅地处理连接错误?

时间:2017-06-09 03:02:45

标签: python python-requests telegram

我有一个简单的python电报机器人,这里是代码:

import requests
import json
from time import sleep
import os

filename = 'bot_last_update'
target = open(filename, 'r')
update_from_file = target.read()

# check update from file
update_from_file = update_from_file.strip()
last_update = int(update_from_file)

token = xxxx
url = 'https://api.telegram.org/bot%s/' % token

# We want to keep checking for updates. So this must be a never ending loop
while True:
    # My chat is up and running, I need to maintain it! Get me all chat updates
    get_updates = json.loads(requests.get(url + 'getUpdates').content)
    # Ok, I've got 'em. Let's iterate through each one
    for update in get_updates['result']:
        # First make sure I haven't read this update yet
        if last_update < update['update_id']:
            last_update = update['update_id']
            target = open(filename, 'w')
            target.truncate()
            target.write(str(last_update))
            target.close()
            if update['message']['chat']['type'] == 'private':
            # I've got a new update. Let's see what it is.
                if update['message']['text'] == 'do something':
                    requests.get(url + 'sendMessage', params=dict(chat_id=update['message']['chat']['id'], text='doing it'))
                    os.system('/srv/scripts/do_something.sh')
                    sleep(10)
                    requests.get(url + 'sendMessage', params=dict(chat_id=update['message']['chat']['id'], text='done!'))
                else:
                    pass
    # Let's wait a few seconds for new updates
    sleep(1)

它运行正常,但每次我的网络出现问题时都会出现此错误:

Traceback (most recent call last):
  File "my_telegram_bot.py", line 21, in <module>
    get_updates = json.loads(requests.get(url + 'getUpdates').content)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 70, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 596, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 473, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(113, 'No route to host'))

避免该错误的最佳方法是什么?我想在任何时候保持这个机器人,所以它不应该在这些类型的事件中以关键方式失败(或者如果它确实,它应该自动恢复/重启)。

1 个答案:

答案 0 :(得分:2)

您需要实施重试机制。以下是python How to retry after exception in python?中的一个示例。假设连接在合理的时间内自行纠正,重试机制将保持机器人并避免错误。

查看Python requests exception handling以获取捕获特定异常的示例。

结合我们得到的两个例子:

from requests import ConnectionError
import requests
import json
import time
import os
connection_timeout = 30 # seconds

...

# My chat is up and running, I need to maintain it! Get me all chat updates
start_time = time.time()
while True:
    try:
        get_updates = json.loads(requests.get(url + 'getUpdates').content)
        break
    except ConnectionError:
        if time.time() > start_time + connection_timeout:
            raise Exception('Unable to get updates after {} seconds of ConnectionErrors'.format(connection_timeout))
        else:
            time.sleep(1) # attempting once every second
# Ok, I've got 'em. Let's iterate through each one

...

这将重试每秒调用getUpdates 30秒,直到连接权限为止。您可以根据需要将connection_timeout调整为大小,以便覆盖间歇性连接。