装饰器之认证
auth_status = {"username":None,"stat":False} def auth(type): def auth_proc(func): def wrapper(*args,**kwargs): #已经认证通过 if auth_status["username"] and auth_status["stat"]: ret = func(*args,**kwargs) return ret #未认证 文件认证 if type == "file_auth": print("文件认证") usr = input("请输入用户名:").strip() pwd = input("请输入密码:").strip() usr_info = user_info() for info in usr_info : u = eval(info)["username"] p = eval(info)["pwd"] if usr == u and pwd == str(p): auth_status["username"] = usr auth_status["stat"] = True ret = func(*args, **kwargs) return ret else: print("用户名或密码错误") #数据库认证 elif type == "db_auth": print("数据库认证") ret = func(*args, **kwargs) return ret else: pass return wrapper return auth_proc def user_info(): with open("author.txt","r",encoding="utf-8") as f: for data in f: yield data @auth(type="db_auth") def home(): print("欢迎[%s]来到个人页......" % auth_status["username"]) @auth(type="file_auth") def login(): print("欢迎[%s]来到登录页......"%auth_status["username"]) login() home()
认证文件
{"username":"user1","pwd":123}
{"username":"user2","pwd":123}
{"username":"user3","pwd":123}
{"username":"user4","pwd":123}