oslo.db/doc/source/usage.rst
Roman Podoliaka fad6e5c230 Fix usage of oslo.config
- make it possible to create a DBAPI instance given a config instance

- remove usage of global cfg.CONF instance (it's up to a user to pass
  a ConfigOpts instance to oslo.db)

- ensure end applications don't need to import/register/use config
  options directly - instead they pass a config instance to oslo.db
  helpers (EngineFacade.from_config() and DBAPI.from_config() class
  methods)

At the same time, usage of oslo.config remains completely optional as
we provide an API to pass those parameters programatically.

Change-Id: I1a00db7a4200ebdc96f17256ecbad430477e868f
2014-05-27 15:58:22 +03:00

1.3 KiB

Usage

To use oslo.db in a project:

* Session Handling
from oslo.config import cfg
from oslo.db.sqlalchemy import session as db_session

_FACADE = None

def _create_facade_lazily():
    global _FACADE
    if _FACADE is None:
        _FACADE = db_session.EngineFacade.from_config(cfg.CONF)
    return _FACADE

def get_engine():
    facade = _create_facade_lazily()
    return facade.get_engine()

def get_session(**kwargs):
    facade = _create_facade_lazily()
    return facade.get_session(**kwargs)
  • Base class for models usage

    from oslo.db import models
    
    
    class ProjectSomething(models.TimestampMixin,
                           models.ModelBase):
        id = Column(Integer, primary_key=True)
        ...
  • DB API backend support

    from oslo.config import cfg
    from oslo.db import api as db_api
    
    
    _BACKEND_MAPPING = {'sqlalchemy': 'project.db.sqlalchemy.api'}
    
    IMPL = db_api.DBAPI.from_config(cfg.CONF, backend_mapping=_BACKEND_MAPPING)
    
    def get_engine():
        return IMPL.get_engine()
    
    def get_session():
        return IMPL.get_session()
    
    # DB-API method
    def do_something(somethind_id):
        return IMPL.do_something(somethind_id)