python重試裝飾器示例

NO IMAGE

利用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 -*-
[email protected]
#  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()

您可能感興趣的文章:

Python中的各種裝飾器詳解Python中的裝飾器用法詳解詳解Python中的裝飾器、閉包和functools的教程python 裝飾器功能以及函式引數使用介紹Python中的多重灌飾器詳解Python裝飾器由淺入深Python裝飾器decorator用法例項例項講解Python程式設計中@property裝飾器的用法Python自動重試HTTP連線裝飾器Python裝飾器原理與簡單用法例項分析