用装饰器来进行登录验证

user_list=[
    {'name':'tom','passwd':'123'},
    {'name':'ubuntu','passwd':'123'},
    {'name':'centos','passwd':'123'},
    {'name':'jane','passwd':'123'},
]
current_dict = {'username':None,'login':False}
def auth(auth_type = 'filedb'): #验证方式默认为filedb
    def auth_func(func):
        def wrapper(*args,**kwargs):
            print("认证方式是:{}".format(auth_type))
            if auth_type == 'filedb':
                if current_dict['username'] and current_dict['login']:
                    res = func()
                    return  res
                username = input("username:>>>").strip()
                passwd = input("passwd:>>>").strip()
                for user_dict in user_list:
                    if username == user_dict['name'] and passwd == user_dict['passwd']:
                        current_dict['username'] = username
                        current_dict['login'] =True
                        res = func()
                        return res
                    else:
                        print("用户名或密码错误")
            else:
                print("鬼知道认证方式是个啥--->{}".format(auth_type))
        return wrapper
    return auth_func

@auth(auth_type = 'filedb')
def index():
    print("欢迎来到京东主页")
@auth()
def home():
    print("欢迎回家!")

@auth('sssssss')
def shopping_car():
    print("购物车中有........")

if __name__ == '__main__':
    index()
    home()
    shopping_car()

猜你喜欢

转载自www.cnblogs.com/zach0812/p/11333335.html