模仿flask底层,使用类装饰器传参实现web路由功能

# 定义一个空字典用来存储请求路劲及对应的函数地址
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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值