蓝图: 简化大型应用
文档: https://dormousehole.readthedocs.io/en/latest/blueprints.html
Script Demo:
config.py
# -*- coding:utf-8 -*-
# 一般大写
DEBUG = True
app_2.py
# -*- coding:utf-8 -*-
from app import create_app
# 创建
app = create_app()
if __name__ == '__main__':
# 启动
app.run(host='0.0.0.0', port=5001)
pro_dir/app/__init__.py
# -*- coding:utf-8 -*-
from flask import Flask
def create_app():
app = Flask(__name__)
app.config.from_object('config')
# 蓝图注册
register_blueprint(app)
return app
# 蓝图注册
def register_blueprint(app):
# 注册 api
from app.api.goods import api
app.register_blueprint(api)
# 注册 web
from app.web.goods import web
app.register_blueprint(web)
pro_dir/app/web/goods.py
# -*- coding:utf-8 -*-
from flask import jsonify, Blueprint
# 实例化蓝图对象
web = Blueprint('web', __name__)
@web.route('/web/getgoods')
def get_goods():
result = {
'computer': 9800,
'milk': 5.6
}
return jsonify(result)
@web.route('/web/getgoods2')
def get_goods2():
result = {
'computer': 9800,
'watermelon': 59.6
}
return jsonify(result)
pro_dir/app/api/goods.py
# -*- coding:utf-8 -*-
from flask import Blueprint, jsonify
# 实例化蓝图对象
api = Blueprint('api', __name__)
@api.route('/api/getgoods')
def get_goods():
result = {
'computer': 16800,
'milk': 29.6
}
return jsonify(result)
@api.route('/api/getgoods2')
def get_goods2():
result = {
'computer': 16800,
'watermelon': 99.9
}
return jsonify(result)
Test调用:
http://127.0.0.1:5001/web/getgoods
http://127.0.0.1:5001/web/getgoods2
http://127.0.0.1:5001/api/getgoods
http://127.0.0.1:5001/api/getgoods2
网友评论