import functools
# 第一种
##################################################
def require_permission(permissions):
def decorated(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
has_permissions = permissions
if has_permissions:
return func(*args, **kwargs)
else:
print(403)
return wrapper
return decorated
@require_permission(True)
def foo():
print('foo')
@require_permission(False)
def foo():
print('foo')
# 第二种
#####################################################################
class require_permissions(object):
def __init__(self, permissions):
self.permissions = permissions
def __call__(self, fn):
@functools.wraps(fn)
def decorated(*args, **kwargs):
has_permissions = self.permissions
if has_permissions:
return fn(*args, **kwargs)
else:
print(403)
return decorated
def require_permission(permission):
return require_permissions(permission)
@require_permission(True)
def foo1():
print('foo')
if __name__ == '__main__':
foo()
foo1()