Last active
August 14, 2017 07:10
-
-
Save kunpengku/0fe1e25d9d7305f12a83347df070d157 to your computer and use it in GitHub Desktop.
装饰器检查参数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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