Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OperationalError no such table in Flask with SQLAlchemy

run.py

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

main.py

import database

app = Flask(__name__)

def config():
    app.config.from_object('config.DevConfig')

    # Run SQLAlchemy _that uses app.config_ and add entities if in DEBUG mode
    database.init_db(app)

    import blueprints.auth
    app.register_blueprint(blueprints.auth.auth)

database.py

db = None

def init_db(app):
    global db
    db = SQLAlchemy(app)

    from models import User, Interest, Event

    if app.config['DEBUG']:
        print 'Recreating all db'
        db.create_all() # I DO create everything
        print 'Loading test data'
        ... (here I add some Users and etc. and everything works fine - tests pass)

models.py

from database import db

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

blueprints/auth.py

from models import User

auth = Blueprint('auth', __name__)

@auth.route('/')
def index():
    return str(User.query.get(1).interests)

And so I get

OperationalError: (OperationalError) no such table: user u'SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email, user.passhash AS user_passhash, user.vk_page AS user_vk_page \nFROM user \nWHERE user.id = ?' (1,)

What am I doing wrong?

like image 435
Ben Usman Avatar asked Feb 13 '14 22:02

Ben Usman


2 Answers

For anyone trying to use an in memory database:

from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool

engine = create_engine(
    "sqlite://", 
    connect_args={"check_same_thread": False}, 
    poolclass=StaticPool
)
like image 159
Harsha Laxman Avatar answered Oct 29 '22 18:10

Harsha Laxman


There were few things I had to change to make everything work.

  1. replace DATABASE_URI with SQLALCHEMY_DATABASE_URI parametr in config
  2. replace :memory: sqlite address with /tmp/test.db

Now it works fine.

like image 40
Ben Usman Avatar answered Oct 29 '22 19:10

Ben Usman