Ceph+python对象存储

进行对象存储操作时,使用 Ceph 的 rados Python 库是一个非常直接和高效的方式。下面我将详细介绍如何使用 rados 进行基本的对象存储操作,包括连接到 Ceph 集群、创建池(pool)、写入和读取对象、列出对象等。

# 完整代码
import rados

def main():
    # 连接到 Ceph 集群
    cluster = rados.Rados(conffile='/etc/ceph/ceph.conf', conf=dict(keyring='/etc/ceph/ceph.client.admin.keyring'))
    print("Cluster ID: ", cluster.get_fsid())
    cluster.connect()

    pool_name = 'my_new_pool'

    # 创建池
    if not cluster.pool_exists(pool_name):
        try:
            cluster.create_pool(pool_name)
            print(f"Pool '{pool_name}' created.")
        except Exception as e:
            print(f"Failed to create pool: {e}")
            return

    # 写入对象
    ioctx = cluster.open_ioctx(pool_name)
    object_name = 'my_object'
    data = b'Hello, Ceph!'
    try:
        ioctx.write(object_name, data)
        print(f"Wrote {len(data)} bytes to object '{object_name}'.")
    except Exception as e:
        print(f"Failed to write object: {e}")

    # 读取对象
    try:
        read_data = ioctx.read(object_name)
        print(f"Read data from object: {read_data.decode()}")
    except Exception as e:
        print(f"Failed to read object: {e}")

    # 列出对象
    print(f"Objects in pool '{pool_name}':")
    for obj in ioctx.list_objects():
        print(obj.key)

    # 删除对象
    try:
        ioctx.remove(object_name)
        print(f"Object '{object_name}' removed.")
    except Exception as e:
        print(f"Failed to remove object: {e}")

    # 关闭资源
    ioctx.close()
    cluster.shutdown()

if __name__ == "__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值