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

心不动则不痛 提交于 2021-02-09 08:48:09

问题


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


回答1:


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?




回答2:


You can use SQLAlchemy-Utils for this.

from sqlalchemy import create_engine
from sqlalchemy_utils import database_exits,create_database

def validate_database():
     engine = create_engine('postgres://postgres@localhost/name')
     if not database_exists(engine.url): # Checks for the first time  
         create_database(engine.url)     # Create new DB    
         print("New Database Created"+database_exists(engine.url)) # Verifies if database is there or not.
     else:
         print("Database Already Exists")

call this method in your __init__.py file so that it checks every time your server starts.




回答3:


There's db.create_all() but I think that when you're using migrations you should stick to migration scripts. Something to note is that if you have your migration files all set up (i.e migration folder) then all you need is flask db migrate If you're running this locally, I would stick to doing this command manually. If you're using this on a server, you should probably use a deployment script that does this for you. You can look at fabric (www.fabfile.org) for information on how to run terminal commands



来源:https://stackoverflow.com/questions/56161826/how-can-i-initialize-the-database-automatically-with-sqlalchemy-and-alembic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!