铁雪资源网 Design By www.gsvan.com

利用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()

标签:
装饰器

铁雪资源网 Design By www.gsvan.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
铁雪资源网 Design By www.gsvan.com

评论“python重试装饰器示例”

暂无python重试装饰器示例的评论...