Erick Almeida Erick Almeida - 7 months ago 142
Python Question

Trying to run the sql-alchemy tutorial steps. Can't import db from console (ImportError: cannot import name 'db')

Trying to run the tutorial here: http://flask-sqlalchemy.pocoo.org/2.1/quickstart/ using my app

I have looked at the circular imports problem but I don't think that's it. I'm an absolute beginner to python and flask (and sqlalchemy). My app currently runs, but the database part doesn't

This is the current setup:

mysite
|- __init__.py
|- flask_app.py
|- models.py
|- views.py


init.py

from flask import Flask
app = Flask(__name__)


flask_app.py

from flask import Flask, request, url_for
import random

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:// -- database uri --'
... app continues here


models.py

from app import app
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)

class Foo(db.Model):
... model continues here


views.py

from app import app,models

... views continue here, still not using anything from models


when I run
from mysite import db
in the python console I get:

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

Answer

Declare your db object in __init__.py. The stuff that is declared in __init__.py defines what can be imported under mysite/.

See: What is __init__.py for?

Also consider moving to the application factory pattern.

For example in __init__.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
  app = Flask(__name__)
  app.config['DEBUG'] = True
  ... more application config ...

  db.init_app(app)

  return app

Then in flask_app.py:

from mysite import create_app, db

app = create_app()

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

I point this out because you instantiate the app object twice in the code you've shown. Which is definitely wrong.

Comments