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()