本文整理汇总了Python中alembic.config.Config方法的典型用法代码示例。如果您正苦于以下问题:Python config.Config方法的具体用法?Python config.Config怎么用?Python config.Config使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类alembic.config
的用法示例。
在下文中一共展示了config.Config方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: attributes
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def attributes(self):
"""A Python dictionary for storage of additional state.
This is a utility dictionary which can include not just strings but
engines, connections, schema objects, or anything else.
Use this to pass objects into an env.py script, such as passing
a :class:`sqlalchemy.engine.base.Connection` when calling
commands from :mod:`alembic.command` programmatically.
.. versionadded:: 0.7.5
.. seealso::
:ref:`connection_sharing`
:paramref:`.Config.attributes`
"""
return {}
示例2: build_database
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def build_database(echo=True, tests=False):
""" Applies the schema to the database. Run this command once to build the database. """
engine = session.get_engine(echo=echo)
schema = config_get('database', 'schema', raise_exception=False)
if schema:
print('Schema set in config, trying to create schema:', schema)
try:
engine.execute(CreateSchema(schema))
except Exception as e:
print('Cannot create schema, please validate manually if schema creation is needed, continuing:', e)
models.register_models(engine)
# Put the database under version control
alembic_cfg = Config(config_get('alembic', 'cfg'))
command.stamp(alembic_cfg, "head")
示例3: setup_alembic_config
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def setup_alembic_config(url):
"setting up generic config for alembic migrations"
directory = 'ether_sql/migrations'
config = Config(os.path.join(directory, 'alembic.ini'))
config.set_main_option('script_location', directory)
config.cmd_opts = argparse.Namespace() # arguments stub
x_arg = 'url=' + url
if not hasattr(config.cmd_opts, 'x'):
if x_arg is not None:
setattr(config.cmd_opts, 'x', [])
if isinstance(x_arg, list) or isinstance(x_arg, tuple):
for x in x_arg:
config.cmd_opts.x.append(x)
else:
config.cmd_opts.x.append(x_arg)
else:
setattr(config.cmd_opts, 'x', None)
return config
示例4: _alembic_get_current_rev
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def _alembic_get_current_rev(config, script):
"""
Works sorta like alembic.command.current
:param config: alembic Config
:return: current revision
:rtype: str
"""
config._curr_rev = None
def display_version(rev, _):
for rev in script.get_all_current(rev):
config._curr_rev = rev.cmd_format(False)
return []
with EnvironmentContext(
config,
script,
fn=display_version
):
script.run_env()
if config._curr_rev is not None and ' ' in config._curr_rev:
config._curr_rev = config._curr_rev.strip().split(' ')[0]
return config._curr_rev
示例5: _get_config
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def _get_config(directory, x_arg=None, opts=None):
"""
A helper that prepares AlembicConfig instance.
"""
config = Config(os.path.join(directory, 'alembic.ini'))
config.set_main_option('script_location', directory)
if config.cmd_opts is None:
config.cmd_opts = argparse.Namespace()
for opt in opts or []:
setattr(config.cmd_opts, opt, True)
if x_arg is not None:
if not getattr(config.cmd_opts, 'x', None):
setattr(config.cmd_opts, 'x', [x_arg])
else:
config.cmd_opts.x.append(x_arg)
return config
示例6: __init__
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def __init__(
self,
file_=None,
ini_section="alembic",
output_buffer=None,
stdout=sys.stdout,
cmd_opts=None,
config_args=util.immutabledict(),
attributes=None,
):
"""Construct a new :class:`.Config`
"""
self.config_file_name = file_
self.config_ini_section = ini_section
self.output_buffer = output_buffer
self.stdout = stdout
self.cmd_opts = cmd_opts
self.config_args = dict(config_args)
if attributes:
self.attributes.update(attributes)
示例7: file_config
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def file_config(self):
"""Return the underlying ``ConfigParser`` object.
Direct access to the .ini file is available here,
though the :meth:`.Config.get_section` and
:meth:`.Config.get_main_option`
methods provide a possibly simpler interface.
"""
if self.config_file_name:
here = os.path.abspath(os.path.dirname(self.config_file_name))
else:
here = ""
self.config_args["here"] = here
file_config = SafeConfigParser(self.config_args)
if self.config_file_name:
file_config.read([self.config_file_name])
else:
file_config.add_section(self.config_ini_section)
return file_config
示例8: notify_db
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def notify_db(notify_api, worker_id):
assert 'test_notification_api' in db.engine.url.database, 'dont run tests against main db'
# create a database for this worker thread -
from flask import current_app
current_app.config['SQLALCHEMY_DATABASE_URI'] += '_{}'.format(worker_id)
create_test_db(current_app.config['SQLALCHEMY_DATABASE_URI'])
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ALEMBIC_CONFIG = os.path.join(BASE_DIR, 'migrations')
config = Config(ALEMBIC_CONFIG + '/alembic.ini')
config.set_main_option("script_location", ALEMBIC_CONFIG)
with notify_api.app_context():
upgrade(config, 'head')
yield db
db.session.remove()
db.get_engine(notify_api).dispose()
示例9: create_all_or_upgrade_db
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def create_all_or_upgrade_db(engine, db_url):
# alembic add a lot of import time, so we lazy import
from alembic import command
from alembic.config import Config
from sqlalchemy import inspect
alembic_config_file = os.path.join(os.path.dirname(__file__), 'alembic.ini')
alembic_config = Config(alembic_config_file)
alembic_config.set_main_option('sqlalchemy.url', db_url)
inspector = inspect(engine)
tables = inspector.get_table_names()
if 'deployments' not in tables and 'bentos' not in tables:
logger.debug('Creating tables')
Base.metadata.create_all(engine)
command.stamp(alembic_config, 'head')
else:
logger.debug('Upgrading tables to the latest revision')
command.upgrade(alembic_config, 'heads')
示例10: run_alembic_migration
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def run_alembic_migration(db_uri, log_handler=None, setup_app=True):
if log_handler:
logging.getLogger(migration_name).addHandler(log_handler)
config = Config()
config.set_main_option("script_location", "data:migrations")
config.set_main_option("db_uri", db_uri)
if setup_app:
config.set_main_option("alembic_setup_app", "True")
else:
config.set_main_option("alembic_setup_app", "")
script = ScriptDirectory.from_config(config)
def fn(rev, context):
return script._upgrade_revs("head", rev)
with EnvironmentContext(config, script, fn=fn, destination_rev="head"):
script.run_env()
示例11: main
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = load_full_settings(config_uri, options=options)
engine = engine_from_config(settings, "sqlalchemy.")
wait_for_db(engine)
with engine.begin() as connection:
initdb(connection, drop_all="--force" in options)
app_name = urllib.parse.urlparse(config_uri).fragment
# generate the Alembic version table and stamp it with the latest revision
alembic_cfg = Config("alembic.ini", ini_section=app_name)
command.stamp(alembic_cfg, "head")
示例12: init_config
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def init_config(sql_url=None):
"""Initialize and return the Alembic configuration."""
sqlalchemy_url = sql_url or CONF.sql_connection
if not sqlalchemy_url:
raise RuntimeError("Please specify a SQLAlchemy-friendly URL to "
"connect to the proper database, either through "
"the CLI or the configuration file.")
if sqlalchemy_url and 'sqlite' in sqlalchemy_url:
LOG.warning('!!! Limited support for migration commands using sqlite'
' databases; This operation may not succeed.')
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini')
)
config.barbican_sqlalchemy_url = sqlalchemy_url
config.set_main_option('script_location',
'barbican.model.migration:alembic_migrations')
return config
示例13: init
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def init():
from sqlalchemy import create_engine
from moxie.models import Base
from moxie.core import DATABASE_URL
engine = create_engine(DATABASE_URL)
for table in Base.metadata.tables:
engine.execute("DROP TABLE IF EXISTS \"{}\" CASCADE;".format(table))
Base.metadata.create_all(engine)
import os
from alembic.config import Config
from alembic import command
alembic_cfg = Config(os.path.join(
os.path.abspath(os.path.dirname(__file__)),
"..",
"alembic.ini"
))
command.stamp(alembic_cfg, "head")
示例14: init_config
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def init_config(sql_url=None):
"""Initialize and return the Alembic configuration."""
sqlalchemy_url = sql_url or CONF.sql_connection
if not sqlalchemy_url:
raise RuntimeError("Please specify a SQLAlchemy-friendly URL to "
"connect to the proper database, either through "
"the CLI or the configuration file.")
if sqlalchemy_url and 'sqlite' in sqlalchemy_url:
LOG.warning('!!! Limited support for migration commands using'
' sqlite databases; This operation may not succeed.')
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini')
)
config.barbican_sqlalchemy_url = sqlalchemy_url
config.set_main_option('script_location',
'barbican.model.migration:alembic_migrations')
return config
示例15: _get_alembic_config
# 需要导入模块: from alembic import config [as 别名]
# 或者: from alembic.config import Config [as 别名]
def _get_alembic_config(db_url, alembic_dir=None):
"""
Constructs an alembic Config object referencing the specified database and migration script
directory.
:param db_url Database URL, like sqlite:///<absolute-path-to-local-db-file>. See
https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls for a full list of valid
database URLs.
:param alembic_dir Path to migration script directory. Uses canonical migration script
directory under mlflow/alembic if unspecified. TODO: remove this argument in MLflow 1.1, as
it's only used to run special migrations for pre-1.0 users to remove duplicate constraint
names.
"""
from alembic.config import Config
final_alembic_dir = os.path.join(_get_package_dir(), 'store', 'db_migrations')\
if alembic_dir is None else alembic_dir
# Escape any '%' that appears in a db_url. This could be in a password,
# url, or anything that is part of a potentially complex database url
db_url = db_url.replace('%', '%%')
config = Config(os.path.join(final_alembic_dir, 'alembic.ini'))
config.set_main_option('script_location', final_alembic_dir)
config.set_main_option('sqlalchemy.url', db_url)
return config