python mini服务器框架路由原理

URL_FUNC_DICT = dict()

def route(url):
    def set_func(func):
        # 建立映射关系,即{'/index.py':index()}
        # url是'/index.py'
        # func是index函数引用
        URL_FUNC_DICT[url] =func
        def call_func(*args,**kwargs):
            return func(*args,**kwargs)
        return call_func
    return set_func


@route('/index.py')
def index():
    print('open index.html')
    return 'open index.html'


@route('/center.py')
def center():
    print('open center.html')
    return 'open center.html'


def application(env):
    file_name = env
    # 从字典中找到映射关系,如func返回是index
    func = URL_FUNC_DICT[file_name]
    # 如:即执行index()
    return func()


application('/index.py')
application('/center.py')

 

你可能感兴趣的:(python)