OpenStack ocata版本中通过sqlalchemy操作数据库

参考:https://blog.csdn.net/Jmilk/article/details/52484991

第一步:我们在nova\db\sqlalchemy\migrate_repo\versions添加文件349_thware.py,定义我们的新表

#--*-- coding:utf8--*--
from sqlalchemy import Boolean, Column, DateTime, Integer
from sqlalchemy import MetaData, String, Table

from oslo_log import log as logging


LOG = logging.getLogger(__name__)

TABLE_NAME='thware'
def define_tables(meta):
    # 定义一个 Table 对象
    thware = Table(
        TABLE_NAME, meta,
        Column('id', Integer),
        Column('name', String(length=255)),
        Column('vcs_ip', String(length=255), nullable=False),
        Column('username', String(length=255), nullable=False),
        Column('password', String(length=255), nullable=False),
        mysql_engine='InnoDB')

    return [thware]


def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    # create all tables
    # Take care on create order for those with FK dependencies
    tables = define_tables(meta)

    # 循环创建表列表
    for table in tables:
        try:
            table.create()
        except Exception:
            LOG.info(_LE('Exception while creating table.'))
            raise


def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine
    tables = define_tables(meta)
    tables.reverse()
    for table in tables:
        table.drop() 

然后执行su -s /bin/sh -c "nova-manage db sync" nova

第二步:我们在文件Y:\usr\lib\python2.7\site-packages\nova\db\sqlalchemy\api.py添加我们的api:

@pick_context_manager_reader
def get_thware_info(context):
    session = context.session
    vcenters_info = session.query(models.Thware).all()
    return vcenters_info 

注意前面的装饰器,在我参考的博文中是直接通过以下语句获取session,在ocata版本中,用装饰器实现

session = get_session()

主要分为读数据库和更新数据库(还有异步操作的):

@pick_context_manager_writer
@pick_context_manager_reader 

可以稍微看下代码实现:

def pick_context_manager_writer(f):
    """Decorator to use a writer db context manager.

    The db context manager will be picked from the RequestContext.

    Wrapped function must have a RequestContext in the arguments.
    """
    @functools.wraps(f)
    def wrapped(context, *args, **kwargs):
        ctxt_mgr = get_context_manager(context)
        with ctxt_mgr.writer.using(context):
            return f(context, *args, **kwargs)
    return wrapped


def pick_context_manager_reader(f):
    """Decorator to use a reader db context manager.

    The db context manager will be picked from the RequestContext.

    Wrapped function must have a RequestContext in the arguments.
    """
    @functools.wraps(f)
    def wrapped(context, *args, **kwargs):
        ctxt_mgr = get_context_manager(context)
        with ctxt_mgr.reader.using(context):
            return f(context, *args, **kwargs)
    return wrapped 

第三步:在nova\db\api.py添加我们的api:

def get_thware_info(context):

    return IMPL.get_thware_info(context)
如此我们添加访问数据库新api完成。


猜你喜欢

转载自blog.csdn.net/idwtwt/article/details/80074595