zoukankan      html  css  js  c++  java
  • Flask-分开Models解决循环引用


    在之前我们测试中,所有语句都在同一个文件中,但随着项目越来越大,管理起来有所不便,所以将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)
  • 相关阅读:
    poj 3258
    CodeForces 367E Sereja and Intervals
    Codeforces Round #240 (Div. 2) C Mashmokh and Numbers
    Codeforces Round #240 (Div. 2) D
    zoj 3768 Continuous Login
    2014/4/4做题感悟
    HDU 1878 欧拉回路
    HDU 3018 Ant Trip
    POJ 3694 Network
    Codeforces Round #239 (Div. 2)
  • 原文地址:https://www.cnblogs.com/lanheader/p/13492260.html
Copyright © 2011-2022 走看看