Python使用装饰器模拟用户登陆验证功能示例

时间:2022-09-04 22:17:02

本文实例讲述了Python使用装饰器模拟用户登陆验证功能。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# -*- coding:utf-8 -*-
#!python3
user_list = [
  {'name':'ad1','passwd':'123'},
  {'name':'ad2','passwd':'123'},
  {'name':'ad3','passwd':'123'},
  {'name':'ad4','passwd':'123'}
]
#初始状态,用来保存登陆的用户,
client_dic = {'username':None,'login':False}
#添加新功能
def auth_func(func):
  def wrapper(*args,**kwargs):
    #参数检查,判断是否有用户登录,如果有,不用验证,直接执行函数的功能
    if client_dic['username'] and client_dic['login']:
      res = func(*args,**kwargs)
      return res
    #输入用户名和密码
    username = input('用户名:').strip()
    passwd = input('passwd:').strip()
    #对比列表,检查用户名和密码是否正确
    for user_dic in user_list:
      if username == user_dic['name'] and passwd == user_dic['passwd']:
        client_dic['username'] = user_dic['name']
        client_dic['login'] = True
        res = func(*args,**kwargs)
        return res
    else:
      print('用户名或者密码错误!')
  return wrapper
@auth_func
def index():
  print("欢迎来到主页")
@auth_func
def home(name):
  print("欢迎回家:%s"%name)
@auth_func
def shoppping_car():
  print('购物车里有[%s,%s,%s]'%('奶茶','妹妹','娃娃'))
print(client_dic)
index()
print(client_dic)
home('root')

运行结果:

Python使用装饰器模拟用户登陆验证功能示例

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/qq_33531400/article/details/79324551