Search code examples
flaskflask-sqlalchemyalembic

How can I initialize the database automatically with SQLalchemy and Alembic?


Currently, I run

$ flask db init
$ flask db migrate -m "initialization"
$ flask db upgrade

if the database does not exist. I would like to run this within Python, e.g. something like

app.create_db()

so that I don't have to care about setting the database up. Is that possible?

I use the flask-sqlalchemy and flask-migrations plugins


Solution

  • Obviously, you have installed flask-migrate, flask-sqlalchemy.

    So, you can do like this:

    from flask_sqlalchemy import SQLAlchemy
    from flask import Flask
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
    db = SQLAlchemy(app)
    db.create_all()
    
    

    API DOC: flask.ext.sqlalchemy.SQLAlchemy.create_all

    but your Question has confused me. why restricted by SQLAlchemy and Alembic?