我正在使用python 3和flask,通过flask-migrate(使用alembic)来处理我的SQL迁移。当我运行本地集成测试时,我想每次都重建数据库,以便可以针对我正在测试的每个api调用针对干净的db运行我的API调用(是的,我可以使用sqlite,但是我想检查约束条件是否正确)。
我可以轻松地在命令行上执行以下操作:
mysql -uroot -e 'drop database DBNAME; create database DBNAME;'
FLASK_APP=flask_app.py flask db upgrade
但是出于两个原因,我宁愿在python代码中运行它:
app
对象(由app = Flask(__name__)
创建)具有cli
属性,但是它需要一个上下文对象,并且感觉不像我在使用正确的工具。我希望有app.cli.invoke('db', 'upgrade')
或类似的...
有没有关于如何在没有子cli进程的情况下从代码中调用flask命令的建议?
答案 0 :(得分:0)
这不是很好,但是最后我避免直接使用flask命令,这似乎可以满足我的要求:
from my.app import app, db, initialize_app
from flask_migrate import Migrate
from alembic import command
from my.settings import settings
from sqlalchemy_utils.functions import drop_database, create_database, database_exists
test_db_name = 'test_db'
db_url = f'mysql+pymysql://mysqluser@127.0.0.1/{test_db_name}'
settings.SQLALCHEMY_DATABASE_URI = db_url
def reset():
if database_exists(db_url):
drop_database(db_url)
create_database(db_url)
initialize_app(app) # sets flask config SQLALCHEMY_DATABASE_URI to include test_db
with app.app_context():
config = Migrate(app, db).get_config()
command.upgrade(config, 'head')
答案 1 :(得分:0)
我使用以下模式(请参见下文)。可以在https://flask.palletsprojects.com/en/1.1.x/cli/?highlight=click#application-context
看到另一种方法# file: commands.py
import click
from click import pass_context
from flask.cli import AppGroup, with_appcontext
from flask import current_app
from flask_migrate import Migrate
from alembic import command
from extensions import flask_db as db
db_cli = AppGroup('db', help='Various database management commands.')
@db_cli.command('init')
def db_init():
"""Initialize the database."""
db.create_all()
click.echo("Create all tables.")
@db_cli.command('drop')
def db_drop():
"""Drop the database."""
db.engine.execute("SET FOREIGN_KEY_CHECKS=0;")
db.drop_all()
db.engine.execute("SET FOREIGN_KEY_CHECKS=1;")
click.echo("Drop all tables.")
@db_cli.command('migrate')
def db_migrate():
"Migrate with alembic."
config = Migrate(current_app, db).get_config()
command.upgrade(config, 'head')
@db_cli.command('db_upgrade')
@pass_context
def db_upgrade(ctx):
"""Alias for 'db reset'."""
db_drop.invoke(ctx)
db_init.invoke(ctx)
db_migrate.invoke(ctx)
# file: extensions.py
# Keep your extenstions separate to allow importing without import loops.
from flask_sqlalchemy import SQLAlchemy
flask_db = SQLAlchemy()
# file: app.py (app/__init__.py) wherever your app is built
from extensions import flask_db
app = Flask(__name__)
flask_db.init_app(app) # I'm not sure if the order matters here.
app.cli.add_command(db_cli)
# file: wsgi.py (top level file)
# This file lets you run 'flask' commands (e.g. flask routes)
# noinspection PyUnresolvedReferences
from app import app as application # noqa
# file layout
- /
- app/ (or app.py)
- __init__.py (optional)
- commands.py
- extensions.py
- wsgi.py
用法:flask db upgrade
答案 2 :(得分:0)
是否有任何理由不能简单地包装具有 CLI 的所有逻辑的函数?
类似的东西
# cli.py
def db_init(cli=False):
db.create_all()
if cli:
print("Created all tables")
@app.cli.command('db-init')
def _db_init(): # I'm just a wrapper function
db_init(cli=True)
如果你这样做,就没有理由事后不能简单地这样做:
# some_module.py
from .cli import db_init
db_init()