zoukankan      html  css  js  c++  java
  • 进军装饰器3/3

    装饰器实验需求:

    某网站有20个页面,除index页面无需登录验证外,其它页面均需要进行登录验证,本实验通过装饰器进行模拟,以达到熟练使用装饰器的目的,而不是达到登录验证的目的:

    初级版模拟:

    # -*-coding:utf-8-*-
    # _Author_:George
    user = "George"
    passwd = "123abc"
    def auth(func):
        def wrapper(*args,**kwargs):
            username = input("username:").strip()
            password = input("password:").strip()
            if username == user and password == passwd:
                print("%s has passed authentication!"%user)
                return func(*args,**kwargs)
            else:
                print("Sorry! username or password inccorect!")
        return wrapper
    def index():
        print("Welcome to index page.")
    @auth
    def home():
        print("Welcome to home page.")
        return "from home"
    @auth
    def bbs():
        print("Welcome to bbs page.")
    index()
    print(home())
    bbs()

    终级版模拟:

    # -*-coding:utf-8-*-
    # _Author_:George
    user = "George"
    passwd = "123abc"
    def auth(auth_type):
        def outer_wrapper(func):
            def wrapper(*args,**kwargs):
                if auth_type == "LOCAL":
                    username = input("username:").strip()
                    password = input("password:").strip()
                    if username == user and password == passwd:
                        print("%s has passed authentication!"%user)
                        return func(*args,**kwargs)
                    else:
                        print("Sorry! username or password inccorect!")
                elif auth_type == "LDAP":
                    print("-------LDAP Flow,此处省略-------")
            return wrapper
        return outer_wrapper
    def index():
        print("Welcome to index page.")
    @auth(auth_type="LOCAL")
    def home():
        print("Welcome to home page.")
        return "33[31;1mfrom home33[0m"
    @auth(auth_type="LDAP")
    def bbs():
        print("Welcome to bbs page.")
    index()
    print(home())
    bbs()
  • 相关阅读:
    Android手势锁实现
    网页模板pug基本语法
    React入门看这篇就够了
    我曾站在离你最近的天涯
    一文看懂浏览器事件循环
    Vi编辑网卡
    2019.6.11_MySQL进阶二:主键与外键
    2019.6.13_笔试题目及答案
    2019.6.13_MySQL简单命令的使用
    2019.6.13_SQL语句中----删除表数据drop、truncate和delete的用法
  • 原文地址:https://www.cnblogs.com/wangcx/p/8227728.html
Copyright © 2011-2022 走看看