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

  python

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

The directory structure is as follows:

Full stop
 ├── jade_ims
 │   ├── __init__.py
 │   ├── models.py
 │   └── views
 │       ├── home.py
 │       ├── __init__.py
 │       └── install.py
 └── run.py

All parts unrelated to the code have been removed.run.pyIt’s just a simple callapp.run()

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/run.py", line 1, in <module>
 from jade_ims import app
 File "/mnt/Data/Code/jade-ims/jade_ims/__init__.py", line 9, in <module>
 from jade_ims.views.install import install
 File "/mnt/Data/Code/jade-ims/jade_ims/views/install.py", line 2, in <module>
 from jade_ims.models import User
 File "/mnt/Data/Code/jade-ims/jade_ims/models.py", 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:https://github.com/Xuanwo/jade-ims

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

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

install.py

from jade_ims import app

What the hell? Should be the first mistake

models.py

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()

__init__.py
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',
 'jade_ims.views.install:install'
 bracket
 
 def create_app():
 app = Flask(__name__)
 app.config.from_object('config')
 db.init_app(app)
 
 for path in bps:
 bp = import_string(path)
 app.register_blueprint(bp)
 
 return app