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


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

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


from application import app
from indexController import index_page

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


from application import app

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

   Reprint policy

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