doingmybest
doingmybest

Reputation: 314

"ImportError: cannot import name" using flask_sqlalchemy

I'm working on creating a minimal application as outlined here.

My minimal code is below:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)


app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////sandbox.db'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username


if __name__ == '__main__':
    app.run(debug = True)

The issue I'm running into is when I try to import the db object from an interactive Python shell.

>>> from my_app import db

I systematically get this error message returned

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name db

Here is some context:

My folder is called sandbox, here are the files and their structure within it

.
├── __init__.py
├── alembic
│   ├── README
│   ├── env.py
│   ├── env.pyc
│   ├── script.py.mako
│   └── versions
├── alembic.ini
├── hue.py
├── my_app.py
├── my_app.pyc
├── random_stuff.py
├── sqlalchemy.py
├── sqlalchemy.pyc
└── templates
    └── index.html

I can't find out what I'm doing wrong, I must be missing something very obvious.

Upvotes: 1

Views: 5348

Answers (2)

doingmybest
doingmybest

Reputation: 314

It looks like my issues was caused by the file called sqlalchemy.py within the same folder. Since I've deleted this file I don't have the issue anymore, I guess name of this file was conflicting with the real sqlalchemy module...

Upvotes: 1

Joost Barendregt
Joost Barendregt

Reputation: 406

Your question does not have the full context, but I assume the file above is called my_app/app.py or similar and the directory does not contain a __init__.py file. Python needs that file to see a directory as a module that it can import from. Add an empty file called my_app/__init__.py and the problem should be solved

Upvotes: 0

Related Questions