该项目参考https://coding.imooc.com/class/220.html,深入理解Flask前后端分离场景,在Flask框架基础上进行了一定的扩展来满足需求。
具体源码:https://github.com/LMFrank/Flask_api
Redpoint
Blueprint(蓝图)的缺点:
-
Blueprint本身不是用来拆分视图函数的,应该是用来模块级别的拆分
-
写路由时可能过于繁琐(
v1/book/get
和v1/book/delete
)当然,上述并不满足restful风格,但是依然可以看出类似
url_prefix
的字符在重复写入,且代码逻辑架构不够清晰因此,我们尝试引入Redpoint实现视图函数的拆分
架构图:
项目框架:
实现方式:
redprint.py
实现方式参考了blueprint
,包括route
装饰器,以及注册函数register
。与blueprint
不同的是,通过self.mound
来储存对应参数,到register
中解包,这样便可以将对应参数传给bp,并调用add_url_rule
方法
# -*- coding: utf-8 -*-
class Redprint(object):
def __init__(self, name):
self.name = name
self.mound = []
def route(self, rule, **options):
def decorator(f):
self.mound.append((f, rule, options))
return f
return decorator
def register(self, bp, url_prefix=None):
if url_prefix is None:
url_prefix = '/' + self.name
for f, rule, options in self.mound:
endpoint = options.pop("endpoints", f.__name__)
bp.add_url_rule(url_prefix + rule, endpoint, f, **options)
调用redprint:
app/api/v1/__init__.py
# -*- coding: utf-8 -*-
from flask import Blueprint
from app.api.v1 import user, book
def create_bluprint_v1():
bp_v1 = Blueprint('v1', __name__)
user.api.register(bp_v1)
book.api.register(bp_v1)
return bp_v1
调用blueprint:
app/app.py
# -*- coding: utf-8 -*-
from flask import Flask
def register_blueprints(app):
from app.api.v1 import create_bluprint_v1
app.register_blueprint(create_bluprint_v1(), url_prefix='/v1')
def create_app():
app = Flask(__name__)
app.config.from_object('app.config.settings')
app.config.from_object('app.config.secure')
register_blueprints(app)
return app