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快速排序的实现及运行时间比较

python快速排序的实现及运行时间比较

快速排序的基本思想:首先选定一个数组中的一个初始值,将数组中比该值小的放在左边,比该值大的放在右边,然后分别对左边的数组进行如上的操作,对右边的数组进行如上的操作。(分治+递归) 1.利...

实例讲解Python中函数的调用与定义

调用函数: #!/usr/bin/env python3 # -*- coding: utf-8 -*- # 函数调用 >>> abs(100) 100...

Python中字典和集合学习小结

映射类型:     表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引     与序列不同,映射是无序的,通...

全面分析Python的优点和缺点

Python的优点和缺点 本节内容如下: Python的优点 Python的缺点 使用Python的知名网站 Python的优点 1. 简单 Python的语法非常...

Python通过websocket与js客户端通信示例分析

Python通过websocket与js客户端通信示例分析

具体的 websocket 介绍可见 http://zh.wikipedia.org/wiki/WebSocket  这里,介绍如何使用 Python 与前端 js 进行通信。...