Skip to content

Instantly share code, notes, and snippets.

@mmerickel
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save mmerickel/a408b25588df46a13685 to your computer and use it in GitHub Desktop.

Select an option

Save mmerickel/a408b25588df46a13685 to your computer and use it in GitHub Desktop.
parsing settings from a pastedeploy-style ini file
import logging.config
import os.path
from alembic import context
from sqlalchemy import create_engine, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if hasattr(config, 'config_file_name'):
path = config.config_file_name
here = os.path.abspath(os.path.dirname(path))
logging.config.fileConfig(path, defaults={'here': here})
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
import myapp.model.meta
target_metadata = myapp.model.meta.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
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.
"""
url = config.get_section('sqlalchemy')['url']
engine = create_engine(url, poolclass=pool.NullPool)
connection = engine.connect()
context.configure(
connection=connection,
target_metadata=target_metadata
)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
# global settings in top-level sections
[sqlalchemy]
url = postgresql+psycopg2://user:pass@host/dbname
[alembic]
script_location = myapp:migrations
file_template = %%(rev)s_%%(slug)s
[app:main]
use = myapp
# app-specific settings here
from ConfigParser import SafeConfigParser
import os.path
from pyramid.config import Configurator
from pyramid.path import DottedNameResolver
from pyramid.path import caller_module
DEFAULT_BLACKLIST = (
# stdlib logging
'loggers'
'logger_',
'handlers',
'handler_',
'formatters',
'formatter_',
# pastedeploy
'server:',
'app:',
'filter:',
'composite:',
'pipeline:',
# alembic
'alembic',
)
def load_settings_from_file(filename, blacklist=DEFAULT_BLACKLIST):
here = os.path.abspath(os.path.dirname(filename))
parser = SafeConfigParser({'here': here})
parser.read(filename)
settings = {}
for section in parser.sections():
if any(section.startswith(prefix) for prefix in blacklist):
continue
prefix = section.replace(':', '.')
for k, v in parser.items(section):
settings[prefix + '.' + k] = v
return settings
def config_from_settings(global_config, app_settings):
config_file = global_config.get('__file__')
settings = load_settings_from_file(config_file)
settings.update(app_settings)
caller = caller_module()
resolver = DottedNameResolver(caller)
package = resolver.get_package()
config = Configurator(settings=settings, package=package)
return config
truthy = frozenset(('t', 'true', 'y', 'yes', 'on', '1'))
def asbool(value):
if value is None:
return False
if isinstance(value, bool):
return value
value = str(value).strip()
return value.lower() in truthy
from .settings import config_from_settings
def main(global_config, **app_settings):
config = config_from_settings(global_config, app_settings)
return config.make_wsgi_app()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment