Pythonswiftclient:一般的使用过程是什么?

2024-04-24 04:39:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做的项目要求我在Openstack云实例上上传和下载文件到swift对象存储和从中下载。我有登录到Openstack实例所需的所有API信息,但是我无法从python内部找出如何使用swiftclient。在

我特别尝试从python内部使用swiftclient,而不是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方法至少需要一个标头值。我还不知道什么是swift请求的有效头。在

更重要的是,我不确定这是否是执行快速操作的正确方法。我已经阅读了文档(http://docs.openstack.org/developer/python-swiftclient/swiftclient.html#module-swiftclient.exceptions)和源代码(https://github.com/openstack/python-swiftclient/blob/master/swiftclient/client.py),但发现这两个都有点迟钝。虽然对于有哪些方法以及它们需要什么参数有一些指导,但是对于执行通用swift操作,并没有明确的操作顺序。在

如果有人能就这方面的一般程序提供一些建议或指导,我们将不胜感激。我可以将post_容器请求的解决方案挤出,以解决我自己在其余操作中遇到的问题。在


Tags: 实例方法nameclientidopenstackcontainerconn
2条回答

借用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答案的直接副本:

^{pr2}$

您可以从openstack配置文件获取所有连接信息开放式rc.sh一

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

对于任何希望使用python swiftclient并遇到以下问题的人来说,一个常规的put_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>'})
    swift_conn.put_object(<container name>, <object name>, <data>)
    swift_conn.close()

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

一般的get_object操作如下所示:

^{pr2}$

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

希望和我处于同一位置的人发现这个有用。在

相关问题 更多 >