处理可能出现的错误和异常,重试。

天问 ae14bdb264 Update 'README.md' 9 months ago
README.md ae14bdb264 Update 'README.md' 9 months ago

README.md

tenacity

tenacity 提供了一组装饰器和函数,可以轻松地添加重试逻辑到你的代码中。你可以使用 @tenacity.retry 装饰器来标记一个函数,以便在出现错误时自动重试。你还可以使用 tenacity.retry 函数来手动控制重试逻辑。

Usage

网络异常多试几次

pip install tenacity

import tenacity

max_tries = 60 * 5  # 5 minutes
wait_seconds = 1

@tenacity.retry(
    stop=stop_after_attempt(max_tries),
    wait=wait_fixed(wait_seconds),
    before=before_log(logger, logging.INFO),
    after=after_log(logger, logging.WARN),
)
def fetch_data(url):
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

try:
    data = fetch_data("https://api.example.com/data")
    print(data)
except tenacity.RetryError:
    print("Failed to fetch data after multiple retries")