Roberto Franco
Roberto Franco

Reputation: 3

Flask, SQLAlchemy, Data Tables - ImportError: cannot import name 'db' in Models.py

I'm trying to use Data Tables with Flask and SQLAchemy and I'm facing the

ImportError: cannot import name 'db'

in module Models.py

My project tree:

app
    /common
        __init__.py
        models.py
        toutes.py
    /mod_tables
        ---
    __init__
    config.py

__init__.py

    from flask import Flask, redirect, session
    from app.mod_tables.models import TableBuilder
    from app.config import Config
    from flask_sqlalchemy import SQLAlchemy
    #from flask_migrate import Migrate

    app = Flask(__name__)

    table_builder = TableBuilder()

    app.config.from_object(Config)
    db = SQLAlchemy(app)
    db.init_app(app)
    #migrate = Migrate(app, db)

    from app.common.routes import main
    from app.common import models
    from app.mod_tables.controllers import tables

    # Register the different blueprints
    app.register_blueprint(main)
    app.register_blueprint(tables)

config.py

import os

basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):

    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:///' + os.path.join(basedir, 'spbData-V3560-FRANCO.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False

\common.models.py

from app import db

class TipoPoste(db.Model):
    tp_tipo = db.Column(db.String(35), primary_key=True)
    tp_descricao = db.Column(db.String(255))
    def __repr__(self):
        return '<Tipo Poste {} - {}>'.format(self.tp_tipo, 
            self.tp_descricao)

Thos code gives me the following error:

flask.cli.NoAppException flask.cli.NoAppException: While importing
"app", an ImportError was raised:

Traceback (most recent call last):   File
"c:\users\rfran.v3560-franco\appdata\local\programs\python\python36-32\lib\site-packages\flask\cli.py",
line 235, in locate_app
     __import__(module_name)   File "C:\Users\rfran.V3560-FRANCO\OneDrive\ArquivosLocais\gepoc\app\__init__.py",
line 2, in <module>
    from app.mod_tables.models import TableBuilder   File "C:\Users\rfran.V3560-FRANCO\OneDrive\ArquivosLocais\gepoc\app\mod_tables\models.py",
line 3, in <module>
    from app.common.models import TipoPoste   File "C:\Users\rfran.V3560-FRANCO\OneDrive\ArquivosLocais\gepoc\app\common\models.py",
line 1, in <module>
    from app import db ImportError: cannot import name 'db'

Any hint? Thanks in advance.

Upvotes: 0

Views: 2404

Answers (2)

ibutiti
ibutiti

Reputation: 26

Your error is caused by a circular import.

db is imported from app/init.py into the app/common/models.py module then the entire models.py module, including the db object, is imported into the app/init.py module. This is a circular import of the db object.

Instead, import the specific objects from the models.py file that you need:

init.py

...
from app.common.routes import main
from app.common.models import TipoPoste
from app.mod_tables.controllers import tables
...

That should fix it.

A good practice is not importing entire modules as you've done here. This could cause conflicts in some names that you may not be obvious at first. It'll save you lots of debugging time.

Upvotes: 1

Light.G
Light.G

Reputation: 7264

Try move db object into models.py. I omitted some unnecessary code.

__init__.py

...
from app.common.models import db
...
app = Flask(__name__)
db.init_app(app)
...  

models.py

...
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...

Upvotes: 1

Related Questions