Python is used in combination with multiple decorators to implement Aspect-Oriented AOP programming.

Source: Internet
Author: User

First, rewrite the two callhandler (performancecountcallhandler and cachecallhandler) described in the previous articles.

The Code is as follows:

#-*-Coding: UTF-8-*-# features # Name: module 2 # purpose: # Author: ankier # created: 22-12-2012 # copyright: (c) ankier 2012 # licence: <2012 ~ 2020> # Export 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

 

#-*-Coding: UTF-8-*-# features # Name: module 2 # purpose: # Author: ankier # created: 22-12-2012 # copyright: (c) ankier 2012 # licence: <2012 ~ 2020> # define 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): # Save result = fun (ARGs, kW) _ cache [Key] = {'value': result, 'time': time. time ()} return _ cache [Key] ['value'] Return wrap return _ cachecallhandler

You need a register decorator to manage and register multiple decorator.

#-*- 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

The following describes how to use these classes. cache is at the beginning and performance handler is at the end.

The usage is as follows:

#-*- 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

Running effect:

------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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.