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