1.基础讲解,参考:点击打开链接
2.常见的装饰器模式包括(主要应用):
a.参数检查;
b.缓存;
c.代理;
d.上下文提供者;
a.参数检查
检查接收或返回的参数
# _*_ coding=utf-8 _*_
# __author__ = 'lucas'
from itertools import izip
rpc_info = {}
def xmlrpc(in_=(), out=(type(None),)):
def _xmlrpc(function):
func_name = function.func_name
rpc_info[func_name] = (in_, out)
print "func_name is %s" % func_name
print rpc_info
def _check_types(elements, types):
if len(elements) != len(types):
raise TypeError('argument count is wrong')
# print "this is %s %s" % (elements,types)
typed = enumerate(izip(elements, types))
for index, couple in typed:
arg, of_the_right_type = couple
if isinstance(arg, of_the_right_type):
continue
raise TypeError('arg #%d should be %s' % (index, of_the_right_type))
def __xmlrpc(*args):
checkable_args = args[1:]
# print "that is %s %s" %(checkable_args,checkable_args[1:])
_check_types(checkable_args, in_)
res = function(*args)
if not type(res) in (tuple, list):
checkable_res = (res,)
else:
checkable_res = res
_check_types(checkable_res, out)
return res
return __xmlrpc
return _xmlrpc
class RPCView(object):
@xmlrpc((int, int))
def meth1(self, int1, int2):
print 'received %d and %d' % (int1, int2)
@xmlrpc((str,), (int,))
def meth2(self, phrase):
print 'received %s' % phrase
return 12
print rpc_info
my = RPCView()
my.meth1(1, 2)
my.meth2("2")
b.缓存(暂无)
c.代理
class User(object):
def __init__(self, roles):
self.roles = roles
class Unauthorized(Exception):
pass
def protect(role):
def _protect(function):
def __protect(*args, **kw):
user = globals().get('user')
print user
print user.roles
if user is None or role not in user.roles:
raise Unauthorized("I won't tell you")
return function(*args, **kw)
return __protect
return _protect
tarek = User(('admin', 'user', 'commonuser'))
bill = User(('user', ))
class MySecrets(object):
@protect('admin')
def waffle_recipe(self):
print 'use tons of butter!'
these_are = MySecrets()
user = bill
these_are.waffle_recipe()
user = bill
these_are.waffle_recipe()
d.上下文提供者(暂无)