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()
  • 相关阅读:
    最大流问题
    最短路-Floyd算法和Dijkstra算法
    最小生成树-Prim算法
    最小生成树-Kruskal算法
    MP and KMP
    导出excel表格并合并单元格(不按模板导出)
    导出excel表格(按模板导出)
    datatables和template列表查询分页单元格合并
    datatables的使用
    js对象的使用
  • 原文地址:https://www.cnblogs.com/wangcx/p/8227728.html
Copyright © 2011-2022 走看看