Luoruize
Luoruize

Reputation: 688

Unable to import db object more than once in flask and sqlalchemy

I have a couple of modules: start.py, user.py, projects.py

In start.py I have:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'my_database_URI'
db = SQAlchemy(app)
db.createAll()

I need to use the db object from both user.py and projects.py. If I import it like so:

from start import db

then I get an error if I do this in both modules. If I only import it to user.py, for example - then it works fine. The error I'm getting is "ImportError: cannot import name db".

Is there a way to solve this?

Upvotes: 2

Views: 1633

Answers (1)

Celeo
Celeo

Reputation: 5682

Sounds like 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 start.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.

Upvotes: 3

Related Questions