flask服务 --蓝图进一步模块化:
注意: 路由函数名称在同一蓝图下不可以相同,不同模块下也不可以
Script Demo:
config.py
# -*- coding:utf-8 -*-
# 一般大写
DEBUG = True
app_3.py
# -*- coding:utf-8 -*-
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001)
proj_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 import api
app.register_blueprint(api)
proj_dir/app/api/__init__.py
# -*- coding:utf-8 -*-
from flask import Blueprint
'''
函数名称在同一蓝图下不能相同,跨模块也不可以
'''
# 实例化蓝图对象
api = Blueprint('api', __name__)
# 导入
from app.api import goods, user
proj_dir/app/api/goods.py
# -*- coding:utf-8 -*-
from flask import jsonify
from . import api
@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)
proj_dir/app/api/user.py
# -*- coding:utf-8 -*-
from flask import jsonify
from . import api
@api.route('/api/getusers')
def get_users():
result = {
'host': '0.0.0.0',
'password': '123456'
}
return jsonify(result)
@api.route('/api/getusers2')
def get_users2():
result = {
'host': '0.0.0.1',
'password': 'qwerty'
}
return jsonify(result)
网友评论