Python-swiftclient: 一般的使用流程是什么?

Python-swiftclient: what is the general usage procedure?

我目前正在进行的项目需要我在 Openstack 云实例上的 swift object 存储中上传和下载文件。我拥有登录 Openstack 实例所需的所有 API 信息,但我不知道如何从 python.

内部使用 swift 客户端

我特别尝试从 python 内部使用 swift 客户端,而不是 swift 命令行界面。我需要能够响应 swift 操作期间发生的异常。

我目前连接和发布容器的尝试如下所示:

try:
    opts = dict(tenant_id=<tenant id value>, region_name=<region name>)
    swift_conn = swiftclient.client.Connection(authurl=<auth url>, user=<username>, key=<password>, tenant_name=<tenant name>, os_options=opts)
    swift_conn.post_container(cont)
    swift_conn.close()
except swiftclient.exceptions.ClientException:
    print(traceback.format_exc())

这会失败,因为 post_container 方法需要至少一个 header 值。我一直无法找出什么构成了 swift 请求的有效 header。

更重要的是,我不确定这是否是执行 swift 操作的正确方法。我已通读文档 (http://docs.openstack.org/developer/python-swiftclient/swiftclient.html#module-swiftclient.exceptions) and the source code (https://github.com/openstack/python-swiftclient/blob/master/swiftclient/client.py),但发现两者都有些晦涩难懂。虽然对于有哪些方法以及它们需要哪些参数有一些指导,但没有明确的操作顺序来执行通用 swift 操作。

如果有人能就此的一般流程提供一些建议或指导,将不胜感激。我可能会将解决方案扩展到 post_container 请求,以通过其余操作解决我自己的问题。

我通过大量的反复试验找到了我自己的问题的答案。我陷入的主要陷阱是没有向 Connection 对象提供 auth_version 参数。如果不提供auth_version参数,则默认为1.0,调用的get_auth_1_0方法重建url 错误并失败。

一般的 put_object 操作看起来像这样,对于任何想在这个问题上使用 python-swiftclient 和 运行 的人来说:

    swift_conn = swiftclient.client.Connection(authurl='<url>', user='<user>', key='<password>', tenant_name='<tenant name>', auth_version='2.0', os_options={'tenant_id': '<tenant id>', 'region_name': '<region name>'})
    swift_conn.put_object(<container name>, <object name>, <data>)
    swift_conn.close()

此代码假设您拥有 Openstack 实例所需的信息并且您正在使用特定区域。

一般的get_object操作如下所示:

    swift_conn = swiftclient.client.Connection(authurl='<url>', user='<user>', key='<password>', tenant_name='<tenant name>', auth_version='2.0', os_options={'tenant_id': '<tenant id>', 'region_name': '<region name>'})
    response, object_body = swift_conn.get_object(<container name>, <object_name>)
    swift_conn.close()
    f = open(<filename>, 'wb')
    f.write(object_body)
    f.close()

此代码获取对象并将其内容保存到文件中。

希望与我处于相同位置的人觉得这很有用。

借用 GMeier 的答案,并针对磁盘上的现有文件稍作修改:

open_file = open('path/to/file').read()
swift_conn = swiftclient.client.Connection(authurl='<url>', user='<user>', key='<password>', tenant_name='<tenant name>', auth_version='2.0', os_options={'tenant_id': '<tenant id>', 'region_name': '<region name>'})
swift_conn.put_object(<container name>, <object name>, contents=open_file, content_type='add/type')
swift_conn.close()

Get 是 GMeier 回答的直接复制:

swift_conn = swiftclient.client.Connection(authurl='<url>', user='<user>', key='<password>', tenant_name='<tenant name>', auth_version='2.0', os_options={'tenant_id': '<tenant id>', 'region_name': '<region name>'})
response, object_body = swift_conn.get_object(<container name>, <object_name>)
swift_conn.close()
f = open(<filename>, 'wb')
f.write(object_body)
f.close()

您从 openstack 配置文件中获取所有连接信息 openrc.sh。