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

yipeiwu_com7年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

python django集成cas验证系统

python django集成cas验证系统

加入cas的好处 cas是什么东西就不多说了,简而言之就是单点登陆系统,一处登陆,全网有权限的系统均可以访问. 一次登陆,多个系统互通 cas一般均放置在内网,加入cas验证则必须要求用...

Python创建xml的方法

本文实例讲述了Python创建xml的方法。分享给大家供大家参考。具体实现方法如下: from xml.dom.minidom import Document class write...

python将txt等文件中的数据读为numpy数组的方法

实际中,很多数据都是存为txt文件、csv文件等,但是在程序中处理的时候numpy数组或列表是最方便的。本文简单介绍读入txt文件以及将之转化为numpy数组或列表的方法。 1 将txt...

Python3 正在毁灭 Python的原因分析

Python 3毫不费力地成为发生在Python社区里最糟糕的事。我还记得第一次使用Python的时候,我还在花大量时间在C++这块上,而Python就像是我的一次开光。我可以打开文本编...

Python OpenCV之图片缩放的实现(cv2.resize)

Python OpenCV之图片缩放的实现(cv2.resize)

OpenCV函数原型: cv2.resize(InputArray src, OutputArray dst, Size, fx, fy, interpolation) 参数解释:...