01 Flask构建可扩展的RESTful API—— 自定义红图
自定义宏图是在原本的蓝图基础上对route的功能进行了一次扩展,蓝图被所有的红图所共用,多加了一个url_prefix的功能,即蓝图的url_prefix=‘v1’,宏图的url_prefix='book',我们访问的url会变成
127.0.0.1:5000/v1/book
项目结构如下
创建项目根目录ginger
在项目目录ginger下创建目录libs用来存放公共功能ginger/libs/redprint.py是自定义的红图
class Redprint: 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 = self.name + '+' + \ options.pop("endpoint", f.__name__) bp.add_url_rule(url_prefix + rule, endpoint, f, **options)
在红图中没有定义add_url_rule方法所以我们在 router中先把add_url_rule中需要的参数先保存起来,最后在把蓝图对象传到红图中的时候,在使用、
在根目录ginger下创建包app,在包app下创建api的包用来保存接口,在api包下创建v1的包表示v1版本的所有接口
""" Created by 七月 on 2018/5/8. """ from app.libs.redprint import Redprint from flask import jsonify __author__ = '七月' api = Redprint('book') @api.route('/search') def search(): books = {'name':"zhangbiao"} return jsonify(books)
""" Created by 七月 on 2018/5/8. """ from flask import jsonify from app.libs.redprint import Redprint api = Redprint('user') @api.route('', methods=['GET']) def get_user(): user = {"name":"user"} return jsonify(user)
from flask import Blueprint from app.api.v1 import user, book def create_blueprint_v1(): bp_v1 = Blueprint('v1', __name__) user.api.register(bp_v1) book.api.register(bp_v1) return bp_v1
""" Created by 七月 on 2018/5/8. """ __author__ = 'zhang'
from flask import Flask app = Flask(__name__) def register_blueprints(app): from app.api.v1 import create_blueprint_v1 app.register_blueprint(create_blueprint_v1(), url_prefix='/v1') def create_app(): app.config.from_object('app.config.setting') app.config.from_object('app.config.secure') register_blueprints(app) return app
在app目录下创建配置文件目录config
""" Created by 七月 on 2018/5/7. """
""" Created by 七月 on 2018/5/7. """
在ginger目录下创建启动文件ginger.py
from app import create_app app = create_app() if __name__ == '__main__': app.run(debug=True)