# 定义一个空字典用来存储请求路劲及对应的函数地址
url_dict = dict()
# 定义一个类装饰器
class app(object):
# 初始化
# 定义类的私有属性
__path = None
def __init__(self, func):
# 初始化并接收实例对象
self.func = func
# 将实例对象和路劲添加到字典
url_dict[app.__path] = self
# 实例对象加()调用__call__方法
def __call__(self, *args, **kwargs):
# print('添加额外功能')
return self.func(*args, **kwargs)
# 定义类方法来接收参数
@classmethod
def route(cls, path):
# 获得请求路劲
cls.__path = path
return app
# 根据不同的路径返回不同的网页
def application(file_path):
# 没有改的统一200
head_stauts = "HTTP/1.1 200 OK\r\n"
# url_dict = {'/post.html': post, '/index.html': index, '/login.html': login}
try:
# 如果请求路劲存在则调用相应装饰后的函数
func = url_dict[file_path]
body = func()
except Exception:
# 上面的界面都没有找到,那么我们的返回一个404
head_stauts = "HTTP/1.1 404 not found\r\n"
body = "not page is show"
return head_stauts, body
###############################上面为框架代码############################
# 使用类装饰器传参
@app.route('/post.html') # 1.app.route('/post.html') return app 2.@app ===> post = app(post)
def post():
# 根据路劲返回相应的内容
body = "post page is show"
return body
@app.route('/center.html')
def center():
body = "center page is show"
return body
def login():
body = "login page is show"
return body
def index():
body = "index page is show"
return body
模仿flask底层,使用类装饰器传参实现web路由功能
最新推荐文章于 2023-02-20 21:14:43 发布