import re


URL_FUNC_DICT = dict()


def route(url):
    def set_func(func):
        # URL_FUNC_DICT["/index.py"] = index
        URL_FUNC_DICT[url] = func
        #def call_func(*args, **kwargs):
        #   return func(*args, **kwargs)
        #return call_func
    return set_func


@route("/index.py")   # 相当于 @set_func  # index = set_func(index)  
def index():
    with open("./templates/index.html",encoding="utf-8") as f:
        content = f.read()

    my_stock_info = "哈哈哈哈 这是你的本月名称....."

    content = re.sub(r"\{%content%\}", my_stock_info, content)

    return content
     

@route("/center.py")
def center():
    with open("./templates/center.html",encoding="utf-8") as f:
        content = f.read()

    my_stock_info = "这里是从mysql查询出来的数据。。。"

    content = re.sub(r"\{%content%\}", my_stock_info, content)

    return content


def application(env, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
    
    file_name = env['PATH_INFO']
    # file_name = "/index.py"


    try:
        # func = URL_FUNC_DICT[file_name]
        # return func()
        return URL_FUNC_DICT[file_name]()
    except Exception as ret:
        return "产生了异常:%s" % str(ret)

以前我们去找动态页面的时候是用if判断去找对应的函数,现在可以使用装饰器实现自动添加的字典。
用装饰器完成路由功能
下一步是添加数据库功能

相关文章:

  • 2021-08-20
  • 2022-12-23
  • 2021-11-27
  • 2021-08-27
  • 2021-11-15
  • 2022-12-23
  • 2021-08-04
  • 2021-12-20
猜你喜欢
  • 2022-12-23
  • 2021-10-15
  • 2022-12-23
  • 2021-06-12
  • 2021-06-06
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案