python 多個裝飾器組合應用,實現面向切面之AOP編程

來源:互聯網
上載者:User

首先,需要對上面幾篇介紹的2個callHandler (PerformanceCountCallHandler, CacheCallHandler)進行改寫。

代碼如下:

#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name:        模組2# Purpose:## Author:      ankier## Created:     22-12-2012# Copyright:   (c) Ankier 2012# Licence:     <2012~2020>#-------------------------------------------------------------------------------import timefrom functools import wraps_Cache ={}def PerformanceCountCallHandler():    def _PerformanceCountCallHandler(originalFunc):        def __PerformanceCountCallHandler(fun):            def wrap(args, kw):                glos = originalFunc.func_globals                package = glos['__package__']                model = glos['__name__']                methodName = originalFunc.func_name                                       timeStart = time.time()                                result = fun(args, kw)                                               timeEnd = time.time()                                print 'package:',package,' , model:', model, ' , methodName:',methodName,'. ', timeEnd - timeStart, 's'                                return result             return wrap        return __PerformanceCountCallHandler    return _PerformanceCountCallHandler

 

#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name:        模組2# Purpose:## Author:      ankier## Created:     22-12-2012# Copyright:   (c) Ankier 2012# Licence:     <2012~2020>#-------------------------------------------------------------------------------import timeimport hashlibimport pickleimport sysfrom functools import wraps_Cache ={}def __HashParamsKey(function, args, kw):    glos = function.func_globals    package = glos['__package__']    model = glos['__name__']    methodName = function.func_name        key = pickle.dumps((package, model, methodName, args, kw))    return hashlib.sha1(key).hexdigest()def __IsObsolete(entry, duration):    return time.time() - entry['time'] > durationdef CacheCallHandler(duration = sys.maxint):    def _CacheCallHandler(originalFunc):        def __CacheCallHandler(fun):            def wrap(args, kw):                key = __HashParamsKey(originalFunc, args, kw)                      if key not in _Cache or __IsObsolete(_Cache[key], duration):                    #儲存結果                                    result = fun(args, kw)                    _Cache[key] = {'value': result,                                   'time': time.time()}                                    return _Cache[key]['value']             return wrap        return __CacheCallHandler    return _CacheCallHandler

需要一個管理和註冊多種裝飾器的註冊裝飾器。

#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name:        registerDecorators# Purpose:## Author:      ankier## Created:     23-12-2012# Copyright:   (c) Ankier 2012# Licence:     <2012~2020>#-------------------------------------------------------------------------------def RegisterDecorators(*_decorators):    def _RegisterDecorators(func):        wrap = func        for _deco in _decorators:            __deco = _deco(func)            wrap = __deco(wrap)        return wrap    return _RegisterDecorators

下面看如何使用這些類,cache 在前面, performance handler 在後面。

使用方式如下:

#-*- coding: UTF-8 -*-import timefrom performanceCountCallHandler import PerformanceCountCallHandlerfrom cacheCallHandler import CacheCallHandlerfrom registerDecorators import RegisterDecorators@RegisterDecorators(CacheCallHandler(10000), PerformanceCountCallHandler())def Sum(xx , yy ):    sum = xx + yy    print '------Execute Sum----- '    time.sleep(5)                return sum@RegisterDecorators(CacheCallHandler(1), PerformanceCountCallHandler())def Count(xx , yy ):    sum = xx + yy    print '------Execute Count----- '    time.sleep(5)                return sum

運行效果:

------Execute Sum----- package: None  , model: mainFrame  , methodName: Sum .  5.0 s9package: None  , model: mainFrame  , methodName: Sum .  0.0 s9------Execute Count----- package: None  , model: mainFrame  , methodName: Count .  5.0 s2------Execute Count----- package: None  , model: mainFrame  , methodName: Count .  5.0 s3------Execute Count----- package: None  , model: mainFrame  , methodName: Count .  5.01600003242 s2

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.