• 进军装饰器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()
  • 相关阅读:
    APP上线碰到的问题:Non-public API usage
    点语法
    strlen、strcpy、strcat的实现
    2. I/O模型基本说明
    1. 同步、异步、阻塞、非阻塞
    8. 负载均衡请求转发实现
    7.负载均衡算法
    6. Nginx配置示例-高可用集群
    5. Nginx配置示例-动静分离
    4. Nginx配置示例-负载均衡
  • 原文地址:https://www.cnblogs.com/wangcx/p/8227728.html
Copyright © 2020-2023  润新知