apicrud.database

database.py

Database session management and schema update

created 31-mar-2019 by richb@instantlinux.net

Functions

alembic_migrate(models, version, script_location)

run schema migrations

get_session([scopefunc, scoped, db_url, engine])

open a db session scoped to flask context or celery thread

initialize_db([db_url, engine, redis_conn])

initialize database connectivity

schema_update(db_engine, models)

Run alembic migrations for updating schema

seed_new_db(db_session[, tz_model])

Seed a new db with admin account and related records.

apicrud.database.alembic_migrate(models, version, script_location, migrate=False, db_session=None, schema_maxtime=0, seed_func=None)

run schema migrations

Parameters
  • models (obj) – the models file object

  • version (str) – schema version expected after migration

  • script_location (str) – relative path name of alembic’s env.py

  • migrate (bool) – whether to run alembic migrations

  • db_session (obj) – existing db session

  • schema_maxtime (int) – how long to wait for migration

  • seed_func (function) – function to seed initial records in blank db

apicrud.database.get_session(scopefunc=None, scoped=True, db_url=None, engine=None)

open a db session scoped to flask context or celery thread

Parameters
  • scopefunc (function) – function which returns a unique thread ID

  • scoped (bool) – whether to use scoped session management

  • db_url (str) – URL of database

  • engine (obj) – override engine object (for unit tests)

Returns

session

Return type

obj

apicrud.database.initialize_db(db_url=None, engine=None, redis_conn=None)

initialize database connectivity

Parameters
  • db_url (str) – URL of database

  • engine (obj) – override engine object (for unit tests)

  • redis_conn (obj) – redis connection object override (for unit tests)

apicrud.database.schema_update(db_engine, models)

Run alembic migrations for updating schema

Must be called with mutex for duration of update to prevent race conditions; begin_transaction() does not ensure mutual exclusion.

Parameters
  • db_engine (obj) – connection to database

  • models (obj) – models to generate or update

apicrud.database.seed_new_db(db_session, tz_model=None)

Seed a new db with admin account and related records. Reads records defined in a file db_seed.yaml (or as otherwise specified in the main config.yaml) and places them in the database.

Parameters
  • db_session (obj) – existing db session

  • tz_model (obj) – timezone model [default models.Tz]