简单实现flask route

来源:互联网 发布:明朝 知乎 编辑:程序博客网 时间:2024/06/06 09:06
import re
class NotFlask():
def __init__(self):
self.routers = [];


@staticmethod
def build_router_re(route):
route_regex = re.sub('(<\w+>)',r'(?P\1.+)',route)
route_reg_str = "^{}$".format(route_regex)
print("route_reg_str:"+route_reg_str)
return re.compile(route_reg_str)


def route(self,routh_str):
def decorator(f):
route_pattern = self.build_router_re(routh_str);
self.routers.append((route_pattern,f))
return decorator


def get_match_route(self,path):
for pattern,view_func in self.routers:
m = pattern.match(path)
if m:
return m.groupdict(),view_func


def run(self,path):
route_match = self.get_match_route(path)
if route_match:
kwargs, view_function = route_match
return view_function(**kwargs)
else:
raise ValueError('Route "{}"" has not been registered'.format(path))




if __name__ == '__main__':


app = NotFlask()


@app.route("/")
def hello_world():
return "helloworld"


@app.route("/hello/<username>")
def hello_user(username):
return "Hello {}!".format(username)


print(app.run("/"))

print(app.run("/hello/bin"))


转载:http://python.jobbole.com/80956/

原文分两章,第二章两处地方写错了一丢丢,所以自己手打了一次代码,放在这里。

侵权删








0 0
原创粉丝点击