1

I'm trying to implement the Flask manager for SQLalchemy. When I run python run.py db migrate then python run.py db upgrade, my tables aren't affected. I just removed a field from my models.py file that should be removed from the table.

Here are my files :

root/run.py :

#!flask/bin/python
import sys
sys.path.append("/app")
from app import app
app.run(debug = True)

root/app/__init__.py :

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from app.database import db, db_session, init_db

app = Flask(__name__)
app.config.from_object('settings')

init_db()

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

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

from catalog.views import catalog
app.register_blueprint(catalog)

root/app/database.py :

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mysql://root:root@127.0.0.1/mydb', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
db = declarative_base()
db.query = db_session.query_property()

def init_db():
    import app.models
    db.metadata.create_all(bind=engine)

I think I'm doing it wrong with the manager.run() but I'm not clearly understanding how to run it.

EDIT :

I finally made more simple database settings after iurisilvio's advice :

root/app/__init__.py :

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate

app = Flask(__name__)
app.config.from_object('settings')
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@127.0.0.1/mydb'

db = SQLAlchemy()
db.app = app
db.init_app(app)

migrate = Migrate(app, db)
manager = Manager(app)

from catalogue.views import catalogue
app.register_blueprint(catalogue)

root/run.py :

#!flask/bin/python
import sys
sys.path.append("/app")

from app import app, manager
from flask.ext.migrate import MigrateCommand

manager.add_command('db', MigrateCommand)

app.debug = True
manager.run()

Now it works pretty fine !

1 Answers1

1

Flask-Migrate works with the Flask-SQLAlchemy session. You are creating your session with raw sqlalchemy.

I don't know if it is possible at all. You have to change your database.py to work with Flask-SQLAlchemy.

iurisilvio
  • 4,868
  • 1
  • 30
  • 36
  • 1
    Thanks, I searched after Flask-SQLAlchemy settings and it did the thing ! I edited my post. –  Mar 15 '14 at 13:33
  • 1
    As a minor improvement, you don't have to set `db.app = app`, you can initialize `SQLAlchemy(app)`. This way, you don't need the `db.init_app` too. – iurisilvio Mar 15 '14 at 13:36