欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python重试装饰器示例

程序员文章站 2022-10-11 08:05:50
利用python 写一些网络服务的时候,当网络状况不好,或者资源占用过多,任务拥塞的情况下,总会抛出一些异常,当前任务就被终止了,可以很好的利用@装饰器,写一个重试的装饰器...

利用python 写一些网络服务的时候,当网络状况不好,或者资源占用过多,任务拥塞的情况下,总会抛出一些异常,当前任务就被终止了,可以很好的利用@装饰器,写一个重试的装饰器,这样比较python!
执行结果:

复制代码 代码如下:

warning:root:timed out, retrying in 3 seconds...
warning:root:timed out, retrying in 6 seconds...
warning:root:timed out, retrying in 12 seconds...

复制代码 代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  tanyewei@gmail.com
#  2014/01/27 10:36
import time
import logging
import socket
from functools import wraps

logging.basicconfig(level=logging.debug)

def retry(myexception, tries=4, delay=3, backoff=2, logger=none):
    def deco_retry(f):
        @wraps(f)
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay
            while mtries > 1:
                try:
                    return f(*args, **kwargs)
                except myexception as ex:
                    msg = "%s, retrying in %d seconds..." % (str(ex), mdelay)
                    if logger:
                        logger.warning(msg)
                    else:
                        print msg
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            return str(ex)

        return f_retry

    return deco_retry

@retry(exception, logger=logging)
def check():
    sk = socket.socket()
    sk.settimeout(5)
    sk.connect(('6.6.6.6', 80))

if __name__ == "__main__":
    check()