0

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'
idjaw
  • 25,487
  • 7
  • 64
  • 83
Erick Almeida
  • 13
  • 1
  • 3

1 Answers1

1

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.

Community
  • 1
  • 1
wgwz
  • 2,642
  • 2
  • 23
  • 35
  • Thanks!! That solved it and let me import db in console Doesn't SQLAlchemy need the app as an argument though? The app is still working, but I haven't gone round to using the database yet though. – Erick Almeida Apr 16 '16 at 00:31
  • My mistake, I forget something important. `db.init_app(app)`. Which sets up the `app` instance for Flask-SQLAlchemy. – wgwz Apr 16 '16 at 02:59