2
votes

I am building an app with Flask and Sqlalchemy. My app.py file starts like this:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
from models import User

and my models.py goes like this:

from app import db
class User
....

so when I run python app.py, I get an error saying "cannot import name User". I guess there's a circular import somewhere, I don't understand how to fix it.

But if I create another file run.py with just

from app import app
app.run()

Everything works perfectly. But why does this break circular import? I can't understand this.

1
Are there any other imports used in those files? - dirn

1 Answers

4
votes

You've got it right: this is a circular import problem.

The way that I've gotten around this is by having another file, a shared.py file in the root directory. In that file, create the database object,

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

In your app/init.py, don't create a new db object. Instead, do

from shared import db
db.init_app(app)

In any place that you want to use the db object, including your models file, import it from shared.py:

from shared import db
# do stuff with db

This way, the object in the shared file will have been initialized with the app context, and there's no chance of circular imports.