Flask红图使用

在Flask中,自带有蓝图功能,但是在大型项目中,只使用蓝图会使得项目比较臃肿,所有在蓝图的基础上引入红图的概念,细化蓝图功能,使得项目更加轻巧。

0x01 红图概念

红图主要针对于具体的业务模块,在蓝图之下,一般在设计REST API的时候将版本号作为整体的蓝图,将各个业务模块作为红图,增加项目的颗粒度。

0x02 红图实现

红图的实现,可以参照蓝图的实现,主要核心的功能,设置视图装饰器,以及注册到蓝图上的功能。

1
class Redprint:
2
    def __init__(self, name):
3
        self.name = name
4
        self.mound = []
5
6
    def route(self, rule, **options):
7
        def decorator(f):
8
            self.mound.append((f, rule, options))
9
            return f
10
11
        return decorator
12
13
    def register(self, bp, url_prefix=None):
14
        if url_prefix is None:
15
            url_prefix = '/' + self.name
16
        for f, rule, options in self.mound:
17
            endpoint = self.name + '+' + \
18
                       options.pop("endpoint", f.__name__)
19
            bp.add_url_rule(url_prefix + rule, endpoint, f, **options)  #注册到蓝图(路由,endpoint)

0x03 红图使用

主要使用也是实现的两个主要功能,注册到蓝图上和视图装饰器。
视图装饰器

1
import Redprint
2
api = Redprint('book')
3
4
@api.route('/search')
5
def search():
6
    pass

注册到蓝图上

1
def create_blueprint_v1():
2
    bp_v1 = Blueprint('v1', __name__)  #蓝图
3
4
    user.api.register(bp_v1)  #红图注册
5
    book.api.register(bp_v1)
6
    client.api.register(bp_v1)
7
    token.api.register(bp_v1)
8
    gift.api.register(bp_v1)
9
    return bp_v1