Python 捕获超时并重复请求

标签 python xively

我正在尝试将 Xively API 与 python 一起使用来更新数据流,但偶尔会出现 504 错误,这似乎会结束我的脚本。

我如何捕捉到该错误,更重要的是如何延迟并重试,以便脚本可以继续运行并在一分钟左右后上传我的数据?

这是我正在上传的 block 。

    # Upload to Xivity
    api = xively.XivelyAPIClient("[MY_API_KEY")
    feed = api.feeds.get([MY_DATASTREAM_ID])
    now = datetime.datetime.utcnow()
    feed.datastreams = [xively.Datastream(id='temps', current_value=tempF, at=now)]
    feed.update()

这是我在脚本失败时看到的错误记录:

Traceback (most recent call last):
 File "C:\[My Path] \ [My_script].py", line 39, in <module>
   feed = api.feeds.get([MY_DATASTREAM_ID])
 File "C:\Python34\lib\site-packages\xively_python-0.1.0_rc2-py3.4.egg\xively\managers.py", >line 268, in get
   response.raise_for_status()
 File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\models.py", line 795, >in raise_for_status
   raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 504 Server Error: Gateway Time-out

谢谢,

附言我已经用 [MY_INFO] 替换了我的个人信息,但显然正确的数据出现在我的代码中。

最佳答案

我通常为此使用装饰器:

from functools import wraps
from requests.exceptions import HTTPError
import time

def retry(func):
    """ Call `func` with a retry.

    If `func` raises an HTTPError, sleep for 5 seconds
    and then retry.

    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            ret = func(*args, **kwargs)
        except HTTPError:
            time.sleep(5)
            ret = func(*args, **kwargs)
        return ret
    return wrapper

或者,如果您想多次重试:

def retry_multi(max_retries):
    """ Retry a function `max_retries` times. """
    def retry(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            num_retries = 0 
            while num_retries <= max_retries:
                try:
                    ret = func(*args, **kwargs)
                    break
                except HTTPError:
                    if num_retries == max_retries:
                        raise
                    num_retries += 1
                    time.sleep(5)
            return ret 
        return wrapper
    return retry

然后把你的代码放在这样的函数中

#@retry
@retry_multi(5) # retry 5 times before giving up.
def do_call():
    # Upload to Xivity
    api = xively.XivelyAPIClient("[MY_API_KEY")
    feed = api.feeds.get([MY_DATASTREAM_ID])
    now = datetime.datetime.utcnow()
    feed.datastreams = [xively.Datastream(id='temps', current_value=tempF, at=now)]
    feed.update()

关于Python 捕获超时并重复请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23892210/

相关文章:

javascript - 如何为 Xively 数据流创建 Highstock 图表?

使用 Arduino WiFi Shield 和 Xively (WPA2) 时出现 HTTP 错误

python - 无法在 PyCharm 中导入自定义模块

python删除以 '\u...'开头的单词

python - Django .aggregate() 在 .annotate() 上

arduino - 如何将 Xively MQTT 服务器与 Arduino 结合使用?

javascript - 使用 XivelyJS 将 JS 值发送到 xively

python - Python 中是否可以在循环中跳过固定次数的迭代?

python - 在 Python 中为不同的日期格式创建一个解析函数

node.js - Xively 和 Node-Red