如何使用 SQLalchemy 和 Alembic 自动初始化数据库?

问题描述 投票:0回答:4

目前,我跑步

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

如果数据库不存在。我想在 Python 中运行它,例如类似的东西

app.create_db()

这样我就不用关心数据库的设置了。这可能吗?

我使用

flask-sqlalchemy
flask-migrations
插件

flask flask-sqlalchemy alembic
4个回答
3
投票

您可以使用 SQLAlchemy-Utils 为此

from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, 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")

在您的 _init_.py 文件中调用此方法,以便它在每次服务器启动时进行检查。


1
投票

显然,你已经安装了

flask-migrate, flask-sqlalchemy

所以,你可以这样做:

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文档:flask.ext.sqlalchemy.SQLAlchemy.create_all

但是你的问题让我很困惑。为什么受到

SQLAlchemy
Alembic
的限制?


1
投票

我正在使用 alembic 和 sqlalchemy。

如果你想 alembic 自动创建数据库(如果不存在),你可以编辑 alembic/env.py 并添加一个检查数据库是否存在的方法:

from sqlalchemy import create_engine, exc

def create_db_if_not_exists():
    # create database if not exists
    db_uri      = os.getenv('SQLALCHEMY_DATABASE_URI')
    database    = db_uri.split('/')[-1]
    db_postgres = "/".join(db_uri.split('/')[0:-1])+"/postgres"
    try:
        engine = create_engine(db_uri)
        # Attempt to connect to the database
        with engine.connect() as conn:
            print(f'Database {database} already exists.')
    except exc.OperationalError:
        #raise Exception
        print(f'Database {database} does not exist. Creating now.')
        engine = create_engine(db_postgres) #using postgres db to connect
        ## Attempt to connect to the database
        with engine.connect() as conn:
            conn.execute("commit")
            conn.execute(f'CREATE DATABASE {database};')

然后在执行迁移之前调用它:

def run_migrations_online() -> None:
    
    create_db_if_not_exists()
    ...

0
投票

db.create_all()
,但我认为当您使用迁移时,您应该坚持使用迁移脚本。 需要注意的是,如果您已设置好迁移文件(即迁移文件夹),那么您所需要的就是
flask db migrate
如果您在本地运行此命令,我会坚持手动执行此命令。 如果您在服务器上使用它,您可能应该使用为您执行此操作的部署脚本。您可以查看
fabric
(www.fabfile.org) 以获取有关如何运行终端命令的信息

© www.soinside.com 2019 - 2024. All rights reserved.