Python捕获超时和重复请求

Python捕获超时和重复请求,python,xively,Python,Xively,我试图将Xively API与python结合使用来更新数据流,但偶尔会出现504错误,这似乎结束了我的脚本 我怎样才能捕捉到错误,更重要的是延迟并重试,以便脚本能够继续运行,并在一分钟左右后上载我的数据 这是我上传的地方 # Upload to Xivity api = xively.XivelyAPIClient("[MY_API_KEY") feed = api.feeds.get([MY_DATASTREAM_ID]) now = datetime.dat

我试图将Xively API与python结合使用来更新数据流,但偶尔会出现504错误,这似乎结束了我的脚本

我怎样才能捕捉到错误,更重要的是延迟并重试,以便脚本能够继续运行,并在一分钟左右后上载我的数据

这是我上传的地方

    # 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
回溯(最近一次呼叫最后一次):
文件“C:\[My Path]\[My\[U script].py”,第39行,在
feed=api.feeds.get([MY_DATASTREAM_ID])
文件“C:\Python34\lib\site packages\xively\u python-0.1.0\u rc2-py3.4.egg\xively\managers.py”>第268行,在get中
响应。针对_状态()提出_
文件“C:\Python34\lib\site packages\requests-2.3.0-py3.4.egg\requests\models.py”,第795行,>处于raise\U状态
引发HTTPError(http\u error\u msg,response=self)
requests.exceptions.HTTPError:504服务器错误:网关超时
谢谢


另外,我已经用[my_info]替换了我的个人信息,但很明显,正确的数据出现在我的代码中

您可以在一个循环中插入try/except语句,该循环有一个睡眠计时器,可以在两次尝试之间等待多长时间。大概是这样的:

import time

# 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)]

### Try loop
feed_updated = False
while feed_updated == False:
    try: 
        feed.update()
        feed_updated=True
    except: time.sleep(60)
正如Dano指出的,最好有一个更具体的except语句

### Try loop
feed_updated = False
while feed_updated == False:
    try: 
        feed.update()
        feed_updated=True
    except HTTPError: time.sleep(60) ##Just needs more time.
    except: ## Otherwise, you have bigger fish to fry
        print "Unidentified Error"
        ## In such a case, there has been some other kind of error. 
        ## Not sure how you prefer this handled. 
        ## Maybe update a log file and quit, or have some kind of notification, 
        ## depending on how you are monitoring it. 
### Try loop
feed_updated = False
feed_update_count = 0
while feed_updated == False:
    try: 
        feed.update()
        feed_updated=True
    except: 
        time.sleep(60)
        feed_update_count +=1 ## Updates counter

    if feed_update_count >= 60:    ## This will exit the loop if it tries too many times
        feed.update()              ## By running the feed.update() once more,
                                   ## it should print whatever error it is hitting, and crash
编辑常规except语句

### Try loop
feed_updated = False
while feed_updated == False:
    try: 
        feed.update()
        feed_updated=True
    except HTTPError: time.sleep(60) ##Just needs more time.
    except: ## Otherwise, you have bigger fish to fry
        print "Unidentified Error"
        ## In such a case, there has been some other kind of error. 
        ## Not sure how you prefer this handled. 
        ## Maybe update a log file and quit, or have some kind of notification, 
        ## depending on how you are monitoring it. 
### Try loop
feed_updated = False
feed_update_count = 0
while feed_updated == False:
    try: 
        feed.update()
        feed_updated=True
    except: 
        time.sleep(60)
        feed_update_count +=1 ## Updates counter

    if feed_update_count >= 60:    ## This will exit the loop if it tries too many times
        feed.update()              ## By running the feed.update() once more,
                                   ## it should print whatever error it is hitting, and crash

我通常会为此使用装饰师:

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

除了,我不会使用裸露的
,因为您最终会重试无法修复的错误(如SyntaxError、KeyError等),所以我尝试了这个选项,因为它似乎是这两个选项中比较简单的一个,但现在我又遇到了一个额外的错误。(可能是一个简单的解决方案,但可能需要一些指导)。谢谢在处理上述异常的过程中,发生了另一个异常:回溯(最近一次调用last):文件“C:[MY\u PATH]\[MY\u SCRIPT].py”,第61行,在exception HTTPError:time.sleep(60)中NameError:name'HTTPError'未定义编辑似乎无法识别该错误,可能是因为它不是内置的。老实说,我从未做过特定的错误处理。在这种情况下,我只想在循环中放置一个计数器。请参阅我的编辑原因,这更简单。@gbenj请注意“来自请求。异常导入HTTPError””达诺回答。这应该可以解决你的问题。如果它连续两次超时呢?顺便说一句,似乎您在最后一句
返回包装中有一个错误的缩进。@KurzedMetal我将在一个可以重试N次的版本中进行编辑。