Flask: avoid circular import

One of the common mistakes using Flask is circular import.
To avoid it, we can split one application file into three files:

  1. application.py file includes all the initiations and setup
  2. www.py file includes all the routes and blueprint registrations
  3. manager.py file starts the server

Application

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:abc123@127.0.0.1/mysql"
db = SQLAlchemy(app)

Routes

from application import app
from indexController import index_page


app.register_blueprint(index_page, url_prefix="/user")

Manager

from application import app

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

   Reprint policy


《Flask: avoid circular import》 by Isaac Zhou is licensed under a Creative Commons Attribution 4.0 International License
  TOC