Python Flask框架路由简单实现
Python Flask框架路由的简单实现
也许你听说过Flask框架。也许你也使用过,也使用的非常好。但是当你在浏览器上输入一串路由地址,跳转至你所写的页面,在Flask中是怎样实现的,你是否感到好奇? 如果你不清楚,那就往下看看吧 ~
废话不多说,直接上码!
""" Flask 路由简单实现 map: {"/home":"home", "/login":"login", ...} """ map = dict() def route(path): def decorator(f): print(path, f.__name__, "<-----------start---------->") map[path] = f.__name__ return f return decorator class TestFlaskRoute: def __init__(self, path): self.path = path def find_url(self): try: getattr(TestFlaskRoute, map.get(self.path)).__call__(self) except: print("\033[031m 没有这个路径! \033[0m ") @route("/login") def login(self, *args, **kwargs): print("\033[036m 这个是", self.path, "! \033[0m") pass @route("/home") def home(self, *args, **kwargs): print("\033[036m 这个是", self.path, "! \033[0m") pass @route("/index") def index(self, *args, **kwargs): print("\033[036m 这个是", self.path, "! \033[0m") pass @route("/call") def phone(self, *args, **kwargs): print("\033[036m 这个是", self.path, "! \033[0m") pass if __name__ == '__main__': while True: url = input("请输入URL路径:") app = TestFlaskRoute(url) app.find_url()