(3) 第3章:Redprint红图实现

先把蓝图注册到app上面,在传进去蓝图包的模块名作为参数穿进去
因为蓝图实例写在**init模块上面,所以是一个是传包名v1**

#在app注册蓝图对象
def registe_blueprint(app):
    from app.api.v1 import create_blueprint_v1
    app.register_blueprint(create_blueprint_v1(), url_prefix='/v1')
    # url_prefix 表示/v1开头的url 会去掉,通过实现蓝图的函数create_blueprint_v1进行匹配

然后实例化蓝图对象,传进去包名和__name__,在蓝图上注册视图函数

def create_blueprint_v1():
    bp_v1 = Blueprint('v1', __name__)
    # 假设api有register的方法,后面再实现, url_prefix解决前缀问题
    # book.api.register(bp_v1,url_prefix='/book')
    # user.api.register(bp_v1,url_prefix='/user')
    # url_prefix='/user'参数和模块名是一样的,则可以去掉
    # 在编写红图的时候可以把模块名和url拼接一下
    #在蓝图上面注册红图对象
    book.api.register(bp_v1)
    user.api.register(bp_v1)
    client.api.register(bp_v1)
    token.api.register(bp_v1)
    gift.api.register(bp_v1)
    return bp_v1

创建红图类 Redprint
初始化传入模块名
重写蓝图的route装饰器,初始化一个列表把参数存进列表里面
self.mound.append((rule, endpoint, f, options))
在写一个注册方法:
register:设置url_prefix参数默认为None和传入蓝图对象
传入的url_prefix参数如果为空,则使用初始化的时候传入的模块名
通过循环刚才的列表,调用 蓝图对象.add_url_rule()
把这些视图函数注册到蓝图上
如下图:

class Redprint:
   def __init__(self, name):
       self.name = name
       self.mound = []

   def route(self, rule, **options):
       def decorator(f):
           endpoint = options.pop("endpoint", f.__name__)
           self.mound.append((rule, endpoint, f, options))
           return f
       return decorator

   def register(self, bp, url_prefix=None):
       if url_prefix is None:
           url_prefix = '/' + self.name
       for rule, endpoint, f, options in self.mound:
           rule = url_prefix + rule
           endpoint = self.name + ':' + endpoint
           bp.add_url_rule(rule, endpoint, f, **options)

猜你喜欢

转载自blog.csdn.net/weixin_42504453/article/details/83583613