日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

retry之python重试机制

發(fā)布時間:2023/12/13 综合教程 42 生活家
生活随笔 收集整理的這篇文章主要介紹了 retry之python重试机制 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
安裝 pip install retry
Retry裝飾器

retry(exceptions=Exception, tries=-1, delay=0, max_delay=None, backoff=1, jitter=0, logger=logging_logger):

"""Return a retry decorator.

:param exceptions: an exception or a tuple of exceptions to catch. default: Exception.

:param tries: the maximum number of attempts. default: -1 (infinite).

:param delay: initial delay between attempts. default: 0.

:param max_delay: the maximum value of delay. default: None (no limit).

:param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).

:param jitter: extra seconds added to delay between attempts. default: 0.

fixed if a number, random if a range tuple (min, max)

:param logger: logger.warning(fmt, error, delay) will be called on failed attempts.

default: retry.logging_logger. if None, logging is disabled.

"""

使用

@retry(ZeroDivisionError, tries=3, delay=2)

def make_trouble():


retry_call

def retry_call(f, fargs=None, fkwargs=None, exceptions=Exception, tries=-1, delay=0, max_delay=None, backoff=1,

jitter=0,

logger=logging_logger):

"""

Calls a function and re-executes it if it failed.

:param f: the function to execute.

:param fargs: the positional arguments of the function to execute.

:param fkwargs: the named arguments of the function to execute.

:param exceptions: an exception or a tuple of exceptions to catch. default: Exception.

:param tries: the maximum number of attempts. default: -1 (infinite).

:param delay: initial delay between attempts. default: 0.

:param max_delay: the maximum value of delay. default: None (no limit).

:param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).

:param jitter: extra seconds added to delay between attempts. default: 0.

fixed if a number, random if a range tuple (min, max)

:param logger: logger.warning(fmt, error, delay) will be called on failed attempts.

default: retry.logging_logger. if None, logging is disabled.

:returns: the result of the f function.

"""

該方法和retry裝飾器類似,除了它帶函數(shù)和函數(shù)的參數(shù),他可以動態(tài)的判斷重試次數(shù)

import requests

from retry.api import retry_call

def make_trouble(service, info=None):

if not info:

info = ''

r = requests.get(service + info)

return r.text

def what_is_my_ip(approach=None):

if approach == "optimistic":

tries = 1

elif approach == "conservative":

tries = 3

else:

# skeptical

tries = -1

result = retry_call(make_trouble, fargs=["http://ipinfo.io/"], fkwargs={"info": "ip"}, tries=tries)

print(result)

what_is_my_ip("conservative")


總結(jié)

以上是生活随笔為你收集整理的retry之python重试机制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。