NoteApi
90 строк · 2.7 Кб
1from __future__ import with_statement
2
3import logging
4from logging.config import fileConfig
5
6from flask import current_app
7
8from alembic import context
9
10# this is the Alembic Config object, which provides
11# access to the values within the .ini file in use.
12config = context.config
13
14# Interpret the config file for Python logging.
15# This line sets up loggers basically.
16fileConfig(config.config_file_name)
17logger = logging.getLogger('alembic.env')
18
19# add your model's MetaData object here
20# for 'autogenerate' support
21# from myapp import mymodel
22# target_metadata = mymodel.Base.metadata
23config.set_main_option(
24'sqlalchemy.url',
25str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
26target_metadata = current_app.extensions['migrate'].db.metadata
27
28# other values from the config, defined by the needs of env.py,
29# can be acquired:
30# my_important_option = config.get_main_option("my_important_option")
31# ... etc.
32
33
34def run_migrations_offline():
35"""Run migrations in 'offline' mode.
36
37This configures the context with just a URL
38and not an Engine, though an Engine is acceptable
39here as well. By skipping the Engine creation
40we don't even need a DBAPI to be available.
41
42Calls to context.execute() here emit the given string to the
43script output.
44
45"""
46url = config.get_main_option("sqlalchemy.url")
47context.configure(
48url=url, target_metadata=target_metadata, literal_binds=True
49)
50
51with context.begin_transaction():
52context.run_migrations()
53
54
55def run_migrations_online():
56"""Run migrations in 'online' mode.
57
58In this scenario we need to create an Engine
59and associate a connection with the context.
60
61"""
62
63# this callback is used to prevent an auto-migration from being generated
64# when there are no changes to the schema
65# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
66def process_revision_directives(context, revision, directives):
67if getattr(config.cmd_opts, 'autogenerate', False):
68script = directives[0]
69if script.upgrade_ops.is_empty():
70directives[:] = []
71logger.info('No changes in schema detected.')
72
73connectable = current_app.extensions['migrate'].db.engine
74
75with connectable.connect() as connection:
76context.configure(
77connection=connection,
78target_metadata=target_metadata,
79process_revision_directives=process_revision_directives,
80**current_app.extensions['migrate'].configure_args
81)
82
83with context.begin_transaction():
84context.run_migrations()
85
86
87if context.is_offline_mode():
88run_migrations_offline()
89else:
90run_migrations_online()
91