oslo.db

官方文档 : https://docs.openstack.org/oslo.db/latest/

oslo.db

oslo.db处理库提供数据库连接到不同的后端数据库和各种其他程序的服务.它主要对SQLAlchemy做进一步封装使用.

安装

$ pip install oslo.db

安装最新的SQL后端支持,诸如:

$ pip install psycopg2
$ pip install PyMySQL
$ pip install pysqlite

使用PostgreSQL:

$ sudo apt-get install libpq-dev
$ pip install psycopg2

使用MySQL-python:
PyMySQL是oslo.db以及整个OpenStack的默认MySQL DB API 驱动程序。但是你仍然可以使用MySQL-python作为替代DB API驱动程序。 对于MySQL-python, 你必须为你的发行版安装MySQL客户端开发包。 在Ubuntu上完成如下:

$ sudo apt-get install libmysqlclient-dev
$ pip install MySQL-python

psycopg2用于PostgreSQL,你必须确保为psycopg2安装所需的系统包(PyMySQL是纯Python实现,因此不需要其他系统包)。对于Ubuntu / Debian,是python-dev和libpq-dev。对于Fedora / CentOS - gcc,是python-devel和postgresql-devel。还有一个单独的环境,用于测试MySQL-python。如果你想要运行这些测试,需要在Ubuntu / Debian上安装libmysqlclient-dev,在 Fedora / CentOS上安装mysql-devel 。
oslo.db单元测试系统允许在实际数据库上运行单元测试。目前它支持MySQL,PostgreSQL和SQLite。为了在真正的数据库后端进行测试,您需要在localhost上设置openstack_citest的用户openstack_citest(某些OpenStack项目需要一个名为“openstack_citest”的数据库)。请注意,该用户必须拥有创建和删除数据库的权限。如果测试系统无法连接到后台,则会跳过测试系统。

使用

Session Handling

from oslo_db.sqlalchemy import enginefacade


class MyContext(object):
    "User-defined context class."


def some_reader_api_function(context):
    #这里需要引入一个class
    with enginefacade.reader.using(context) as session:
        return session.query(SomeClass).all()


def some_writer_api_function(context, x, y):
    with enginefacade.writer.using(context) as session:
        session.add(SomeClass(x, y))


def run_some_database_calls():
    context = MyContext()

    results = some_reader_api_function(context)
    some_writer_api_function(context, 5, 10)

注 facade:外观,假象

你可能感兴趣的:(oslo.db)