current_appの説明がしっくりと理解できません。
flaskでORMを書いていますが、調べながら見よう見まねで動かしつつ、flask-migrateを実行してmigrationファイルができるという状況です。
しかし、ちゃんと理解できていません。とりわけ、current_appについて理解できていません。
current_appを理解するためには、公式ドキュメントの以下の点について理解する必要があると思っています。
-
まず、なぜproxyの話がでてくるのか? migrationコマンドを実行する時にthe current requestを送っていないと思います。もし、requestをどこかで送っているとしてら、どの部分でそういうコードをかいているのか?
blueprintsは使っていないし、そもそもapplication factory patternという言葉が曖昧で意味がわからないが使っていいないと思うので関係がないと思うが、import itのitは何をさしているのか?
migrationを実行するときに、このアプリケーションを実行するためにたてるサーバーとは別にもう一つmigrationようにサーバーをたててrunしているのか?それは、以下のコードのどの部分で行われているのか?
以下、公式ドキュメントからの抜粋
http://flask.pocoo.org/docs/1.0/api/#flask.current_app
flask.current_app A proxy to the application handling the current request. This is useful to access the application without needing to import it, or if it can’t be imported, such as when using the application factory pattern or in blueprints and extensions. This is only available when an application context is pushed. This happens automatically during requests and CLI commands. It can be controlled manually with app_context(). This is a proxy. See Notes On Proxies for more information.
以下、実際にちゃんと理解せず使ってなんとか動かしている箇所
python
from flask import Flask from flask_sqlalchemy import SQLAlchemy from c.config import test from flask_migrate import Migrate current_app = Flask(__name__) from c.models.models import db current_app.config['JSON_AS_ASCII'] = False current_app.config.from_object(test) migrate = Migrate(current_app, db) with current_app.app_context(): config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) target_metadata = db.metadata ... ... ... def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, 'autogenerate', False): script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] logger.info('No changes in schema detected.') engine = engine_from_config(config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool) connection = engine.connect() context.configure(connection=connection, target_metadata=target_metadata, process_revision_directives=process_revision_directives, **current_app.extensions['migrate'].configure_args) try: with context.begin_transaction(): context.run_migrations() finally: connection.close() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
まだ回答がついていません
会員登録して回答してみよう