python中装饰器的使用和类装饰器在类中方法的使用

前面一遍讲述了装饰器的基本知识,正好最近有个系统需要进行权限控制,那么我们就实例分析下装饰器的使用。装饰器是一个面向切面编程,主要作用就是权限控制,插入日志,性能测试,事务处理,缓存等。


对于重要的系统我们仅仅控制登录是不够的,对于固定人员使用到的系统我们还是要进行权限的细分。下面是bollte框架下的一个简单的例子。

def www_auth(func):
    '''
    装饰器限制ip访问功能
    '''
    def wrapper(*args,**kargs):
        ips = ['192.168.1.1']
        remoteip = request.environ.get('REMOTE_ADDR')
        #print remoteip
        if remoteip in ips:
            return func(**kargs)
        else:
            redirect('/error')
    return wrapper


#我们再函数的前面加@www_auth即可,这个是对index请求限制的例子。
@route('/index', method='GET')
@www_auth
def index():
    #其他逻辑代码
    return template('html/test.html')

@route('/error',method='GET')
def error():
    return template('html/error.html')

当非192.168.1.1的ip访问过后将会跳转到错误的页面。

下面的例子是类装饰器对类中的方法进行装饰。


class Foo(object):
    def __init__(self):
        pass

    def __call__(self,func):
        def _call(*args,**kw):
            print 'class decorator runing'
            return func(*args,**kw)
         return _call
 
class Bar(object):
    @Foor()
    def bar(self,test,ids):
        print 'bar'
 
Bar().bar('aa','ids')
                      


我们经常会用到的比如说给多线程函数加锁来保证共享数据操作的完整性。

线程锁装饰器如下:

class StandardOut(object): 
   """ 
   线程锁装饰器
   """ 
   def __init__(self):
       self.thread_lock = threading.Lock()
    
   def __call__(self,func):
       def _call(*args,**kw): 
           self.thread_lock.acquire()
           func(*args,**kw)
           self.thread_lock.release()
       return _call




猜你喜欢

转载自blog.csdn.net/nextdoor6/article/details/53502353
今日推荐