Python使用装饰器模拟用户登陆验证功能示例
作者:我是马克思小清新 时间:2022-03-04 20:56:52
本文实例讲述了Python使用装饰器模拟用户登陆验证功能。分享给大家供大家参考,具体如下:
# -*- 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程序设计有所帮助。
来源:https://blog.csdn.net/qq_33531400/article/details/79324551
标签:Python,装饰器,登陆验证
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python的endswith()的使用方法及实例
2023-04-30 04:42:11
![](https://img.aspxhome.com/file/2023/6/85266_0s.png)
python爬虫 urllib模块url编码处理详解
2021-09-13 02:24:37
python中os操作文件及文件路径实例汇总
2023-03-20 23:54:09
numba提升python运行速度的实例方法
2022-10-06 20:39:27
PyTorch中apex安装方式和避免踩坑
2023-06-20 15:19:57
![](https://img.aspxhome.com/file/2023/8/61438_0s.png)
Python实现新年愿望代码雨效果
2022-08-02 00:52:35
![](https://img.aspxhome.com/file/2023/6/72186_0s.jpg)
Python中五种实现字符串反转的方法
2023-11-08 00:22:12
![](https://img.aspxhome.com/file/2023/0/109440_0s.png)
pytorch中的优化器optimizer.param_groups用法
2023-02-12 08:10:08
Python学习之MRO方法搜索顺序
2022-01-25 13:08:12
![](https://img.aspxhome.com/file/2023/9/99439_0s.png)
python 下载文件的多种方法汇总
2023-08-11 16:50:05
![](https://img.aspxhome.com/file/2023/7/105017_0s.gif)
解析:怎样掌握SQL Server中的数据查询
2009-01-19 13:30:00
pandas读取csv文件提示不存在的解决方法及原因分析
2022-10-27 19:08:02
Python OpenCV实现3种滤镜效果实例
2021-06-04 10:20:27
![](https://img.aspxhome.com/file/2023/3/64233_0s.jpg)
Python实现寻找回文数字过程解析
2022-06-21 10:48:04
css表单中textarea域背景图片设置方法
2008-04-21 13:56:00
Oracle 数据库自动存储管理-安装配置
2009-05-24 19:15:00
浅谈SQL Server中统计对于查询的影响分析
2012-06-06 20:08:23
Django实现文件上传下载
2022-03-17 18:42:48
URL编码“陷阱”
2008-03-04 16:57:00
浅谈Python中的bs4基础
2022-11-05 16:57:47