接上文基础(3),假如又有新的需求:在用户登录时候,加一个token验证功能,怎么破?
见代码:
#basic4.py #coding:utf-8 def login(key): local_key = "78A7AS78AAGD68AH23JB23JH34J2JH42JH46N35NK24235SDMmasdaldjkasldkasdkla" if local_key == key: return True else: return False def auth(func): def inner(*arg, **kwargs): print 'before' # key = kwargs['token'] # del kwargs['token'] key = kwargs.pop('token') #kwargs.pop相当于上面2句,先取出key,然后删除key。 is_login = login(key) if not is_login: return '非法用户!' # func代指 fetch_server_list 原函数 temp = func(*arg,**kwargs) print 'after' return temp return inner @auth def fetch_server_list(arg): serve_list = ['c1','c2','c3'] return serve_list
执行部分:
#b4.py import basic4 key = "78A7AS78AAGD68AH23JB23JH34J2JH42JH46N35NK24235SDMmasdaldjkasldkasdkla" ret_list = basic4.fetch_server_list('test',token=key) print ret_list
执行结果:
#python b4.py before after ['c1', 'c2', 'c3']