Python随心记--函数闭包为函数加上认证功能
函数闭包为函数加上认证功能
def auth_func(func): def wrapper(*args,**kwargs): user_name = input('用户名:').strip() user_pass = input('密 码:').strip() if user_name == 'achun' and user_pass == 77770000: ret = func(*args,**kwargs) return ret else: print('账户或密码错误!') return wrapper @auth_func def index(): print('欢迎来到京东') @auth_func def home(name): print('欢迎%s回家' %name) @auth_func def shopping_car(name,names,namess): print('购物车的东西【%s,%s,%s】' %(name,names,namess)) index() home('achun') shopping_car('奶茶','篮球','裤子')
函数闭包模拟session 目前知识:全局变量
user_list = [ {'user':'alex','pass':'123456'}, #这里注意数据类型 {'user':'async','pass':'123456'}, {'user':'lauencess','pass':'123456'} ] current_dic= {'user':None,'login':False} def auth_func(func): def wrapper(*args,**kwargs): if current_dic['user'] and current_dic['login']: ret = func(*args, **kwargs) return ret username = input('用户名:').strip() userpass = input('密 码:').strip() for user_dic in user_list: if username == user_dic['user'] and userpass == user_dic['pass']: ret = func(*args,**kwargs) current_dic['user'] = username current_dic['login'] = True return ret else:#若整个循环都未找到对应的账户和密码将会退出 print('账户或密码错误!') return wrapper @auth_func def index(): print('欢迎来到京东') @auth_func def home(name): print('欢迎%s回家' %name) @auth_func def shopping_car(name,names,namess): print('购物车的东西【%s,%s,%s】' %(name,names,namess)) index() home('achun') shopping_car('奶茶','篮球','裤子')
函数闭包带参数装饰器 添加应用场景
user_list = [ {'user':'alex','pass':'123456'}, #这里注意数据类型 {'user':'async','pass':'123456'}, {'user':'lauencess','pass':'123456'} ] current_dic= {'user':None,'login':False} def auth( auth_type = 'filedb'): #可以传一个场景 def auth_func(func): def wrapper(*args, **kwargs): #print('场景是%s' %auth_type) if auth_type == 'filedb': if current_dic['user'] and current_dic['login']: ret = func(*args, **kwargs) return ret username = input('用户名:').strip() userpass = input('密 码:').strip() for user_dic in user_list: if username == user_dic['user'] and userpass == user_dic['pass']: ret = func(*args, **kwargs) current_dic['user'] = username current_dic['login'] = True return ret else: # 若整个循环都未找到对应的账户和密码将会退出 print('账户或密码错误!') elif auth_type == 'Mongodb': print('这里执行另外的操作') else: print('这里执行另外的操作') return wrapper return auth_func @auth(auth_type = 'filedb') #auth_func = auth(auth_type = 'filedb') def index(): print('欢迎来到京东') @auth(auth_type = 'Mongodb') #auth_func = auth(auth_type = 'filedb') def home(name): print('欢迎%s回家' %name) @auth(auth_type = 'Redis') #auth_func = auth(auth_type = 'filedb') def shopping_car(name,names,namess): print('购物车的东西【%s,%s,%s】' %(name,names,namess)) @auth(auth_type = 'Memcached') #auth_func = auth(auth_type = 'filedb') def detailed_list(name,names,namess): print('购物车的东西【%s,%s,%s】' %(name,names,namess)) index() home('achun') shopping_car('奶茶','篮球','裤子')