Skip to content

Instantly share code, notes, and snippets.

@kunpengku
Last active August 14, 2017 07:10
Show Gist options
  • Save kunpengku/0fe1e25d9d7305f12a83347df070d157 to your computer and use it in GitHub Desktop.
Save kunpengku/0fe1e25d9d7305f12a83347df070d157 to your computer and use it in GitHub Desktop.
装饰器检查参数
def check_is_admin(f):
def wapper(*args, **kwargs):
if kwargs.get('username') != 'admin':
raise Exception('This user is not allowed to get')
return f(*args, **kwargs)
return wapper
class Store(object):
@check_is_admin
def get_food(self, username, food):
return self.storage.get(food)
@check_is_admin
def put_food(self, username, food):
return self.storage.put(food)
import functools
#改进版, 原来装饰器创建的新函数 会缺少 原函数的很多属性, functools提供了一个工具, 将这些属性加回来。
def check_is_admin(f):
@functools.wraps(f)
def wapper(*args, **kwargs):
if kwargs.get('username') != 'admin':
raise Exception('This user is not allowed to get')
return f(*args, **kwargs)
return wapper
class Store(object):
@check_is_admin
def get_food(self, username, food):
return self.storage.get(food)
@check_is_admin
def put_food(self, username, food):
return self.storage.put(food)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment