python学习,day4:装饰器的使用示例2

Python装饰器实现用户鉴权
本文介绍如何使用Python的装饰器模式来实现用户本地鉴权功能,通过定义不同的鉴权类型,如本地鉴权和LDAP鉴权,来增强函数的安全性和灵活性。文章详细展示了装饰器的三层结构,以及如何在不同场景下应用这些装饰器。

这个例子比较复杂

# coding=utf-8
# Author: RyAn Bi
user,passwd = 'bb','123'   #输入用户名密码
def auth(auth_type):        #装饰器第一层,确定鉴权类型
    print('auth func:', auth_type )    #打印鉴权类型
    def out_wrapper(func):       #装饰器第二层,调用函数
        def warrper(*args,**kwargs):    #装饰器第三层,增加功能,具体实施
            if auth_type == 'local':        #判断鉴权类型
                username = input('username:').strip()   #输入用户名
                password = input('password:').strip()   #输入密码
                if user==username and passwd ==password:   #判断用户密码
                    print('\033[32;1mthe user is correct\033[0m')
                    res =func(*args,**kwargs)  #from home    #运行程序,并将程序运行结果导入res
                    print('=======>after authentication')
                    return res     #返回func       #将res结果返回给func,home程序输出‘from home
                else:
                   exit('\033[31;1mthe user is invalid\033[0m')
            elif auth_type =='ldap':
                print('搞毛线啊,不会')
        return warrper
    return out_wrapper

def index():
    print('welcom to index page')
@auth(auth_type = 'local')   #home =auth()
def home():
    print('welcom to home page')
    return 'from home'
@auth(auth_type = 'ldap')
def bbs():
    print('welcom to bbs page')

index()
print(home())  #调用home相当于调用warrper

bbs()

 

转载于:https://www.cnblogs.com/bbgoal/p/10438142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值