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

天问 b26787cdac Update 'README.md' 1 year ago
README.md b26787cdac Update 'README.md' 1 year ago

README.md

tenacity

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

Usage

网络异常多试几次

pip install tenacity

import tenacity

@tenacity.retry
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")