使用Python Swift客户端将文件上传到OpenStack

iklwldmw  于 2022-11-21  发布在  Swift
关注(0)|答案(1)|浏览(217)

有人能提供一个完整的示例,说明如何使用Python Swift客户端将文件上传到OpenStack容器中吗?https://pypi.org/project/python-swiftclient/
包括以下内容:

  • 针对OpenStack示例进行身份验证
  • 调用相关函数将文件上传到OpenStack容器

谢谢

iqxoj9l9

iqxoj9l91#

我可以用下面的代码来实现

from keystoneauth1 import session
from keystoneauth1.identity import v3
from swiftclient.client import Connection

# Create a password auth plugin
auth = v3.Password(
    auth_url='https://cloud.company.com:5000/v3/',
    username='myaccount',
    password='mypassword',
    user_domain_name='Default',
    project_name='myproject',
    project_domain_name='Default'
)

# Create session
keystone_session = session.Session(auth=auth)

# Create swiftclient Connection
swift_conn = Connection(session=keystone_session)

# Create container
swift_conn.put_container('test')

# Read file
with open('myfile.txt', 'rb') as f:
    file_data = f.read()

# Upload file
swift_conn.put_object('test', 'myfile.txt', file_data)

相关问题