Python3.5——装饰器及应用详解(下)
来源:互联网 发布:gitlab 使用 windows 编辑:程序博客网 时间:2024/06/05 15:15
1、装饰器应用——模拟网站登录页面,访问需要认证登录页面
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:ZhengzhengLiu#模拟网站,访问页面和部分需要登录的页面import timeruser,passwd = "liu","liu123"def auth(func): def wrapper(*args,**kwargs): username = input("Username:").strip() password = input("Password:").strip() if username == user and password == passwd: print("\033[32;1mUser has passed authentication!\033[0m") res = func(*args,**kwargs) print("-----after authentication---") return res else: exit("\033[31;1mInvalid username or password!\033[0m") return wrapperdef index(): print("welcome to index page!")@authdef home(): print("welcome to index home!") return "from home"@authdef bbs(): print("welcome to index bbs!")#函数调用index()print(home())bbs()#运行结果:#welcome to index page!#Username:liu#Password:liu123#User has passed authentication!#welcome to home page!#-----after authentication---#from home#Username:liu#Password:liu123#User has passed authentication!#welcome to bbs page!#-----after authentication---
2、装饰器带参数
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:ZhengzhengLiu#模拟网站,访问页面和部分需要登录的页面,多种认证方式import timeruser,passwd = "liu","liu123"def auth(auth_type): print("auth func:",auth_type) def outer_wrapper(func): def wrapper(*args, **kwargs): print("wrapper func args:",*args, **kwargs) if auth_type == "local": username = input("Username:").strip() password = input("Password:").strip() if username == user and password == passwd: print("\033[32;1mUser has passed authentication!\033[0m") #被装饰的函数中有返回值,装饰器中传入的参数函数要有返回值 res = func(*args, **kwargs) #from home print("-----after authentication---") return res else: exit("\033[31;1mInvalid username or password!\033[0m") elif auth_type == "ldap": print("ldap....") return wrapper return outer_wrapperdef index(): print("welcome to index page!")@auth(auth_type="local") #利用本地登录 home = wrapper()def home(): print("welcome to home page!") return "from home"@auth(auth_type="ldap") #利用远程的ldap登录def bbs(): print("welcome to bbs page!")#函数调用index()print(home()) #wrapper()bbs()运行结果:
阅读全文
0 0
- Python3.5——装饰器及应用详解(下)
- Python3.5——装饰器及应用详解(上)
- Python3.5——装饰器之案例剖析
- 解除装饰器作用(python3新增)
- python3 装饰器
- Python3 装饰器
- Python3之装饰器
- python3 核心 装饰器
- python3 装饰器
- Python3 装饰器
- Python3 装饰器
- Python3.5——文件读与写详解(下)
- 设计模式——装饰器模式及在jdk中的应用
- Java I/O 技术(四)—— 装饰设计模式及应用 初识
- 装饰器模式--介绍、应用及代码
- Python中的装饰器及@用法详解
- python3.3 装饰器日志
- python3学习笔记:装饰器
- 牛客《剑指Offer》 反转链表
- jdbc调用存储过程获取多个结果集
- linux中Oops信息的调试及栈回溯
- 手机黑域ADB开启教程
- 输入时触发事件,解决中文输入时的触发问题
- Python3.5——装饰器及应用详解(下)
- postgreSQL存储过程写法示例
- UVA 10763
- php 实用函数
- 关闭Cadence 原理图 弹出startpage 页面的方法:
- 长时间辕们所忽视得WEB-INF目录下文件权限问题
- 欧拉函数思路
- Yii 高级 前后端自动分离
- mysql 关于密码修改