主程序入口manages.py:
import app
my_app=app.create_app()
if __name__ == '__main__':
my_app.run(debug=True)
项目初始化配置文件_init_.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from app.views.acc import acc
from app.views.user import user
db=SQLAlchemy()
def create_app():
my_app=Flask(__name__)
my_app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:1234@127.0.0.1:3306/db_unv?charset=utf8"
# SQLALCHEMY_POOL_SIZE 配置 SQLAlchemy 的连接池大小
my_app.config["SQLALCHEMY_POOL_SIZE"] = 5
# SQLALCHEMY_POOL_TIMEOUT 配置 SQLAlchemy 的连接超时时间
my_app.config["SQLALCHEMY_POOL_TIMEOUT"] = 15
my_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(my_app) #初始化app app与sqlalchemy产生关联
my_app.register_blueprint(acc)
my_app.register_blueprint(user)
return my_app
程序在加载前需要指定的配置,及蓝图注册使用会在此处被完成。
蓝图的测试代码:
from flask import Blueprint
acc=Blueprint("acc",__name__)
@acc.route("/acc",methods=["POST","GET"])
def get_acc():
return "这是acc蓝图"
from flask import Blueprint
user=Blueprint("user",__name__)
@user.route("/user",methods=["POST","GET"])
def get_user():
return "这是user蓝图"
创建数据库模型关系类:models.py
from app import db,create_app
class User(db.Model):
__tablename__='user'
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String(32),index=True)
if __name__ == '__main__':
my_app=create_app()
db.drop_all(app=my_app) #执行表操作前清空数据
db.create_all(app=my_app)