使用Python装饰器重试请求

2024-06-07 07:37:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我的脚本中有多个函数,它们执行restapi API请求。如我需要处理的错误场景我已经把一个重试机制如下。在

no_of_retries = 3
def check_status():
    for i in range(0,no_of_retries):
        url = "http://something/something"
        try:
            result = requests.get(url, auth=HTTPBasicAuth(COMMON_USERNAME, COMMON_PASSWORD)).json()
            if 'error' not in result:
                return result
            else:
                continue
        except Exception as e:
            continue
    return None

我有几种不同的方法可以做类似的操作。我们怎样才能更好地避免重复可能是使用装饰器。在


Tags: of函数noin脚本apirestapiurl
2条回答

与其使用decorator,可能更好的解决方案是将请求移动到它自己的函数中,从而得到类似于以下内容的结构:

no_of_retries = 3

def make_request(url):
    for i in range(0,no_of_retries):
        try:
            result = requests.get(url, auth=HTTPBasicAuth(COMMON_USERNAME, COMMON_PASSWORD)).json()
            if 'error' not in result:
                return result
            else:
                continue
        except Exception as e:
            continue
    return result

def check_status():
    result = make_request("http://something/status")

def load_file():
    result = make_request("http://something/file")

这样,在封装请求时可以避免重复的代码。如果要使用decorator,则需要包装整个load_file()方法,这将阻止您在此函数中进一步处理请求的结果。在

如果不介意安装库,可以使用^{}github.com/jd/tenacity)模块。其中一个例子是:

import random
from tenacity import retry, stop_after_attempt

# @retry  # retry forever
@retry(stop=stop_after_attempt(3))
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is hosed!!!111one")
    else:
        return "Awesome sauce!"

print(do_something_unreliable())

这还允许您指定要继续重试的尝试次数或秒数。在

对于您的情况,这可能看起来像这样(未经测试!)公司名称:

^{pr2}$

相关问题 更多 >

    热门问题