# encoding=utf-8
from keystoneauth1 import session
from keystoneauth1.identity import v3
from swiftclient import client,ClientException
OS_USERNAME = 'admin'
OS_USER_DOMAIN_NAME = 'Default'
OS_PASSWORD = '123456'
OS_PROJECT_NAME = 'admin'
OS_PROJECT_DOMAIN_NAME = 'Default'
OS_AUTH_URL = 'http://192.169.113.11:35357/v3'
# Create a password auth plugin
auth = v3.Password(auth_url=OS_AUTH_URL,
username=OS_USERNAME,
password=OS_PASSWORD,
user_domain_name=OS_USER_DOMAIN_NAME,
project_name=OS_PROJECT_NAME,
project_domain_name=OS_PROJECT_DOMAIN_NAME)
# Create session
keystone_session = session.Session(auth=auth)
# Create swiftclient Connection
swift_conn = client.Connection(session=keystone_session)
# List the available containers (列出可用的容器)------------------------------
resp_headers, containers = swift_conn.get_account()
print("Response headers: %s" % resp_headers)
for container in containers:
print(container)
# # List the available objects(列出可用对象)------------------------------
container = 'container-lsy'
resp_headers, objects = swift_conn.get_container(container)
print("Response headers: %s" % resp_headers)
for object in objects:
print(object)
# # Create a new container(创建一个新容器)------------------------------
container = 'container-lsy2'
swift_conn.put_container(container)
resp_headers, containers = swift_conn.get_account()
if container in containers:
print("The container was created")
for container in containers:
print(container)
# # Create a new object with the contents of a local text file(创建具有本地文本文件内容的新对象)------------------------------
container = 'container-lsy'
with open('data/123.pdf', 'rb') as local:
swift_conn.put_object(
container,
'123.pdf',
contents=local,
content_type='text/plain'
)
## list object(列表对象)----------------------------------------
container = 'container-lsy'
resp_headers,body = swift_conn.get_object(container, '123.pdf')
print(resp_headers)
## Confirm presence of the object(确认物体的存在)------------------------------
obj = '123.pdf'
container = 'container-lsy'
try:
resp_headers = swift_conn.head_object(container, obj)
print('The object was successfully created')
except ClientException as e:
if e.http_status == '404':
print('The object was not found')
else:
print('An error occurred checking for the existence of the object')
# # # Download the created object(下载创建的对象)------------------------------
resp_headers, obj_contents = swift_conn.get_object(container, obj)
with open('local_copy.pdf', 'wb') as local:
local.write(obj_contents)
# # Delete the created object(删除创建的对象) -------------------------------------
obj = '123.pdf'
container = 'container-lsy'
try:
swift_conn.delete_object(container, obj)
print("Successfully deleted the object")
except ClientException as e:
print("Failed to delete the object with error: %s" % e)
文档:https://ecloud.10086.cn/op-help-center/develop/Swift%20Python%20SDK.pdf