Friday, 15 July 2011

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



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

i have couple of modules: start.py, user.py, projects.py

in start.py have:

from flask import flask flask.ext.sqlalchemy import sqlalchemy app = flask(__name__) app.config['sqlalchemy_database_uri'] = 'my_database_uri' db = sqalchemy(app) db.createall()

i need utilize db object both user.py , projects.py. if import so:

from start import db

then error if in both modules. if import user.py, illustration - works fine. error i'm getting "importerror: cannot import name db".

is there way solve this?

sounds circular import problem.

the way i've gotten around having file, shared.py file in root directory. in file, create database object,

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

in start.py, don't create new db object. instead, do

from shared import db db.init_app(app)

in place want utilize db object, including models file, import shared.py:

from shared import db # stuff db

this way, object in shared file have been initialized app context, , there's no chance of circular imports.

python flask flask-sqlalchemy

1 comment: