在之前我们测试中,所有语句都在同一个文件中,但随着项目越来越大,管理起来有所不便,所以将Models分离.
基本的文件结构如下
—–app.py
—–models.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from models import Article app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./Article.db' SQLALCHEMY_TRACK_MODIFICATIONS = False db = SQLAlchemy(app) # db.create_all() @app.route('/') def index(): return 'index' if __name__ == '__main__': #最好关闭debug app.run()
from app import db class Article(db.Model): __tablename__='article' id = db.Column(db.Integer,primary_key=True) title = db.Column(db.String(100),nullable=False) content = db.Column(db.Text,nullable=False)
但此时会出现循环引用的错误,也就是你需要我的,我需要你的,错误如下图
解决方法
新建一个exts.py文件
—–app.py
—–models.py
—–exts.py
exts.py文件内容如下
from flask_sqlalchemy import SQLAlchemy #此时先不传入app db = SQLAlchemy()
app.py更改如下
去掉from flask_sqlalchemy import SQLAlchemy
增加db.init_app(app)
from flask import Flask from models import Article app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./Article.db' SQLALCHEMY_TRACK_MODIFICATIONS = False db.init_app(app) # db.create_all() @app.route('/') def index(): return 'index' if __name__ == '__main__': #最好关闭debug app.run()
models.py
from exts import db class Article(db.Model): __tablename__='article' id = db.Column(db.Integer,primary_key=True) title = db.Column(db.String(100),nullable=False) content = db.Column(db.Text,nullable=False)