用字典的key-value代替if语句;并且value为函数的引用,实现c语言中函数指针的思想。
URL_FUNC_DICT= dict() # 全局变量;将函数引用保存为字典的value
def route(url):
def set_func(func):
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():
with open("./templates/index.html") 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") as f:
content = f.read()
my_stock_info = "这里是从mysql查询出来的数据。。。"
content = re.sub(r"{%content%}", my_stock_infor, content)
return content
try:
return URL_FUNC_DICT[file_name] # 代替if语句,由字典key-value映射关系代替if语句
except Exception as ret:
return "产生了异常:%s" % str(ret)