Erick Almeida Erick Almeida - 6 months ago 98x
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: 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:


from flask import Flask
app = Flask(__name__)

from flask import Flask, request, url_for
import random

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

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

db = SQLAlchemy(app)

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

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'


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

See: What is for?

Also consider moving to the application factory pattern.

For example in

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

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


  return app

Then in

from mysite import create_app, db

app = create_app()

if __name__ == '__main__':

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