Python实现带参数的用户验证功能装饰器示例

yipeiwu_com7年前Python基础

本文实例讲述了Python实现带参数的用户验证功能装饰器。分享给大家供大家参考,具体如下:

user_list = [
  {'name': 'sb1', 'passwd': '123'},
  {'name': 'sb2', 'passwd': '123'},
  {'name': 'sb3', 'passwd': '123'},
  {'name': 'sb4', 'passwd': '123'}
]
# 初始状态,用来保存登陆的用户,
client_dic = {'username': None, 'login': False}
# 添加新功能
def auth(auth_type='filedb'):
  def auth_func(func):
    def wrapper(*args, **kwargs):
      print(auth_type)
      if auth_type == 'fildb':
      # 参数检查,判断是否有用户登录,如果有,不用验证,直接执行函数的功能
        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('用户名或者密码错误!')
      elif auth_type == 'pass':
        print('不知道什么验证方式')
        res = func(*args, **kwargs)
        return res
      else:
        print('一脸蒙蔽的验证方式')
        res = func(*args, **kwargs)
        return res
    return wrapper
  return auth_func
@auth(auth_type='filedb')
def index():
  print("欢迎来到主页")
@auth(auth_type='user')
def home(name):
  print("欢迎回家:%s" % name)
@auth(auth_type='pass')
def shoppping_car():
  print('购物车里有[%s,%s,%s]' % ('奶茶', '妹妹', '娃娃'))
print(client_dic)
index()
print(client_dic)
home('root')

运行结果:

{'username': None, 'login': False}
filedb
一脸蒙蔽的验证方式
欢迎来到主页
{'username': None, 'login': False}
user
一脸蒙蔽的验证方式
欢迎回家:root

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

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

相关文章

Django框架模板文件使用及模板文件加载顺序分析

Django框架模板文件使用及模板文件加载顺序分析

本文实例讲述了Django框架模板文件使用及模板文件加载顺序。分享给大家供大家参考,具体如下: 模板功能 产生html,控制页面上产生的内容。模板文件不仅仅是一个html文件。 模板文件...

Python实现高效求解素数代码实例

素数是编程中经常需要用到的。 作为学习Python的示例,下面是一个高效求解一个范围内的素数的程序,不需要使用除法或者求模运算。 #coding:utf-8 #设置python...

如何修复使用 Python ORM 工具 SQLAlchemy 时的常见陷阱

在使用 SQLAlchemy 时,那些看似很小的选择可能对这种对象关系映射工具包的性能产生重要影响。 对象关系映射Object-relational mapping(ORM)使应用程序开...

Python实现远程调用MetaSploit的方法

本文较为详细的讲述了Python实现远程调用MetaSploit的方法,对Python的学习来说有很好的参考价值。具体实现方法如下: (1)安装Python的msgpack类库,MSF官...

Python max内置函数详细介绍

Python max内置函数 max(iterable, *[, key, default]) max(arg1, arg2, *args[, key]) Return the larg...