Using Blueprint and Flask (web framework) _ SQLAlchemy in Flask (web framework) Framework


Using Blueprint and in Flask (web framework) FrameworkFlask_SQLAlchemyEncountered the problem of circular import.

The directory structure is as follows:

Full stop
 ├── jade_ims
 │   ├──
 │   ├──
 │   └── views
 │       ├──
 │       ├──
 │       └──

All parts unrelated to the code have been’s just a simple

jade_imsUnder the directory__init__.pyThe import part of the file is as follows:

from flask import Flask
 from flask_sqlalchemy import SQLAlchemy
 from jade_ims.views.home import home
 from jade_ims.views.install import install

models.pyThe import part of is as follows:

from jade_ims import db

viewsUnder the directoryinstall.pyThe import section is as follows:

from flask import Blueprint, render_template, g
 from jade_ims.models import User

The error reporting prompt is as follows:

Traceback (most recent call last):
 File "/mnt/Data/Code/jade-ims/", line 1, in <module>
 from jade_ims import app
 File "/mnt/Data/Code/jade-ims/jade_ims/", line 9, in <module>
 from jade_ims.views.install import install
 File "/mnt/Data/Code/jade-ims/jade_ims/views/", line 2, in <module>
 from jade_ims.models import User
 File "/mnt/Data/Code/jade-ims/jade_ims/", line 1, in <module>
 from jade_ims import db
 ImportError: cannot import name 'db'

I want to operate directly in the view when I need it.dbcarry throughSelect,InsertWait for the operation.

The full source code can be found here:

Excuse me, is there something wrong with me? Thank you all.

I just learned from flask (web framework), too, so just say it.

from jade_ims import app

What the hell? Should be the first mistake

from jade_ims import db

If init init is to be placed, the view Blueprint view must first be registered and then the db class loop must be imported

from flask_sqlalchemy import SQLAlchemy
 db = SQLAlchemy()
It is too ugly to instantiate one lump of factory functions.

from flask import Flask
 from werkzeug.utils import import_string
 from config import config
 from models import db
 bps = ['jade_ims.views.home:home',
 def create_app():
 app = Flask(__name__)
 for path in bps:
 bp = import_string(path)
 return app