Why do I keep getting 'ImportError: cannot import name db'?
You are correct you have a circle import issue.
At app.py
you import from noteapp.models import db
,
and at models.py
you import from noteapp.app import app
A quick fix could be:
at models.py
use db = SQLAlchemy()
without the app
.
At the app.py
module, import db from models.py and do db.init_app(app)
also remove db = SQLAlchemy(app)
from your app.py
your app.py should look like this..
from noteapp.models import db
...
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'removed for reasons'
...
def init_db():
db.init_app(app)
db.app = app
db.create_all()
...
if __name__ == '__main__':
app.init_db()
app.run(debug=True)
models.py should look like this:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
email = db.Column(db.String(80), primary_key=True, unique=True)
password = db.Column(db.String(80))
def __init__(self, email, password):
self.email = email
self.password = password
def __repr__(self):
return '<User %r>' % self.email