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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

启动Atom并运行python文件的步骤

启动Atom并运行python文件的步骤

atom(一款开源的代码编辑器)是github专门为程序员推出的一个跨平台文本编辑器。具有简洁和直观的图形用户界面,并有很多有趣的特点:支持CSS,HTML,JavaScript等网页编...

教你使用python画一朵花送女朋友

教你使用python画一朵花送女朋友

本文实例为大家分享了用python画一朵花的具体代码,供大家参考,具体内容如下 第一种,画法 from turtle import * import time setup(60...

Python编程入门之Hello World的三种实现方式

本文实例讲述了Python编程入门之Hello World的三种实现方式。分享给大家供大家参考,具体如下: 第一种方式: $python >>>print('hel...

详解python while 函数及while和for的区别

详解python while 函数及while和for的区别

1.while循环(只有在条件表达式成立的时候才会进入while循环) while 条件表达式:   pass while 条件表达式:   pass else:   pass 不知道...

Python中的集合介绍

Python中的集合介绍

1.集合的定义 集合的元素是不可重复的 s = {1,2,3,1,2,3,4,5} print(s) print(type(s)) s1 = {1} print(s1) print(...