装饰器添加模拟用户登陆页面(基础版)


###装饰器模拟登陆
##需求,就是比如之前的网站没有没有登陆页面,现在我需要加上一个登陆的需求
##这一步只是写在本地的用户信息,用来测试的
user,password = "caicai","13421731046"
##装饰里面的功能(3)
def auth(func):
##然后定义一个内嵌函数(3-1)
def wrapper(*args,**kwargs):##传入参数,以备不时之需
##现在可以开始判断用户的输入了
userInput = input("user:").strip()
passwordInput = input("password:").strip()
if userInput == user and passwordInput == password:
print("33[32:1m Welcome to 33[0m")
##用户登陆完成后应该要执行它之前的功能了
res = func(*args,**kwargs)
return res
else:
exit("33[31:1m login failure 33[0m")
return wrapper
##比如现在有两个页面要登陆(1)这个比如是之前原本就有的了
def index():
print("welcome to index page")
##先把功能名字写上吧(2)
@auth
##注意装上装饰器后本来的功能上的返回值已经不在home身上了
##想要拿回返回结果就在谁调用了它的后面returnres = func(*args,**kwargs) return res
def home():
print("welcome to home page")
@auth
def bbs():
print("welcome to bbs page")
##home页面和bbs页面需要加上登陆页面

##调用
index()
home()
bbs()
 
以上内容作为课堂笔记,如有雷同,请联系于我
原文地址:https://www.cnblogs.com/ArtisticMonk/p/8931658.html