本文整理汇总了Python中swiftclient.Connection.put_container方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.put_container方法的具体用法?Python Connection.put_container怎么用?Python Connection.put_container使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类swiftclient.Connection
的用法示例。
在下文中一共展示了Connection.put_container方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SwiftBackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class SwiftBackend(BakthatBackend):
"""Backend to handle OpenStack Swift upload/download."""
def __init__(self, conf={}, profile="default"):
BakthatBackend.__init__(self, conf, profile)
from swiftclient import Connection, ClientException
self.con = Connection(self.conf["auth_url"],
self.conf["access_key"],
self.conf["secret_key"],
auth_version=self.conf["auth_version"],
tenant_name=self.conf["tenant_name"],
insecure=self.conf["insecure"])
region_name = self.conf["region_name"]
if region_name == DEFAULT_LOCATION:
region_name = ""
try:
self.con.head_container(self.conf["s3_bucket"])
except ClientException, e:
self.con.put_container(self.conf["s3_bucket"])
self.container = self.conf["s3_bucket"]
self.container_key = "s3_bucket"
示例2: SwiftBackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class SwiftBackend(duplicity.backend.Backend):
"""
Backend for Swift
"""
def __init__(self, parsed_url):
try:
from swiftclient import Connection
from swiftclient import ClientException
except ImportError:
raise BackendException("This backend requires "
"the python-swiftclient library.")
self.resp_exc = ClientException
conn_kwargs = {}
# if the user has already authenticated
if os.environ.has_key('SWIFT_PREAUTHURL') and os.environ.has_key('SWIFT_PREAUTHTOKEN'):
conn_kwargs['preauthurl'] = os.environ['SWIFT_PREAUTHURL']
conn_kwargs['preauthtoken'] = os.environ['SWIFT_PREAUTHTOKEN']
else:
if not os.environ.has_key('SWIFT_USERNAME'):
raise BackendException('SWIFT_USERNAME environment variable '
'not set.')
if not os.environ.has_key('SWIFT_PASSWORD'):
raise BackendException('SWIFT_PASSWORD environment variable '
'not set.')
if not os.environ.has_key('SWIFT_AUTHURL'):
raise BackendException('SWIFT_AUTHURL environment variable '
'not set.')
conn_kwargs['user'] = os.environ['SWIFT_USERNAME']
conn_kwargs['key'] = os.environ['SWIFT_PASSWORD']
conn_kwargs['authurl'] = os.environ['SWIFT_AUTHURL']
if os.environ.has_key('SWIFT_AUTHVERSION'):
conn_kwargs['auth_version'] = os.environ['SWIFT_AUTHVERSION']
else:
conn_kwargs['auth_version'] = '1'
if os.environ.has_key('SWIFT_TENANTNAME'):
conn_kwargs['tenant_name'] = os.environ['SWIFT_TENANTNAME']
self.container = parsed_url.path.lstrip('/')
try:
self.conn = Connection(**conn_kwargs)
self.conn.put_container(self.container)
except Exception, e:
log.FatalError("Connection failed: %s %s"
% (e.__class__.__name__, str(e)),
log.ErrorCode.connection_failed)
示例3: SwiftBackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class SwiftBackend(duplicity.backend.Backend):
"""
Backend for Swift
"""
def __init__(self, parsed_url):
try:
from swiftclient import Connection
from swiftclient import ClientException
except ImportError:
raise BackendException("This backend requires " "the python-swiftclient library.")
self.resp_exc = ClientException
conn_kwargs = {}
# if the user has already authenticated
if os.environ.has_key("SWIFT_PREAUTHURL") and os.environ.has_key("SWIFT_PREAUTHTOKEN"):
conn_kwargs["preauthurl"] = os.environ["SWIFT_PREAUTHURL"]
conn_kwargs["preauthtoken"] = os.environ["SWIFT_PREAUTHTOKEN"]
else:
if not os.environ.has_key("SWIFT_USERNAME"):
raise BackendException("SWIFT_USERNAME environment variable " "not set.")
if not os.environ.has_key("SWIFT_PASSWORD"):
raise BackendException("SWIFT_PASSWORD environment variable " "not set.")
if not os.environ.has_key("SWIFT_AUTHURL"):
raise BackendException("SWIFT_AUTHURL environment variable " "not set.")
conn_kwargs["user"] = os.environ["SWIFT_USERNAME"]
conn_kwargs["key"] = os.environ["SWIFT_PASSWORD"]
conn_kwargs["authurl"] = os.environ["SWIFT_AUTHURL"]
if os.environ.has_key("SWIFT_AUTHVERSION"):
conn_kwargs["auth_version"] = os.environ["SWIFT_AUTHVERSION"]
else:
conn_kwargs["auth_version"] = "1"
if os.environ.has_key("SWIFT_TENANTNAME"):
conn_kwargs["tenant_name"] = os.environ["SWIFT_TENANTNAME"]
self.container = parsed_url.path.lstrip("/")
try:
self.conn = Connection(**conn_kwargs)
self.conn.put_container(self.container)
except Exception, e:
log.FatalError("Connection failed: %s %s" % (e.__class__.__name__, str(e)), log.ErrorCode.connection_failed)
示例4: swift_upload
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
def swift_upload(container, path, auth, user, key):
conn = SwiftConnection(auth, user, key, snet=False, insecure=True)
put_headers = { 'x-object-meta-mtime': "%f" % getmtime(path) }
retry = SWIFT_RETRY_TIMES
while retry > 0:
try:
with open(path, 'rb') as fd:
conn.put_object(container, path, fd,
content_length=getsize(path), headers=put_headers)
return True
except ClientException:
log_normal(logger, {
'action': 'upload-error',
'error': 'swift client exception'
}, LOG_ERROR)
conn.put_container(container, headers={})
retry -= 1
return False
示例5: SwiftStorage
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class SwiftStorage(object):
def __init__(self, *args, **kwargs):
super(SwiftStorage, self).__init__()
self.__dict__.update(kwargs)
config_data = get_config_json()
# Load config variables.
self.auth_url = config_data.get('swift').get('auth_url')
self.access_key = config_data.get('swift').get('access_key')
self.secret_key = config_data.get('swift').get('secret_key')
self.auth_version = config_data.get('swift').get('auth_version')
self.tenant_name = config_data.get('swift').get('tenant_name')
self.insecure = True
self.container = config_data.get('swift').get('container')
self.name_backup = kwargs.get('name_backup', None)
self.conn = Connection(
authurl=self.auth_url,
user=self.access_key,
key=self.secret_key,
auth_version=self.auth_version,
tenant_name=self.tenant_name,
insecure=self.insecure)
try:
self.conn.head_container(self.container)
except:
self.conn.put_container(self.container)
if not self.name_backup:
raise SystemExit(_error_codes.get(103))
def send_file(self, filename, **kwargs):
try:
backup_file = open(filename, 'rb')
response = self.conn.put_object(
self.container, filename, backup_file)
print('Uploading file {0} to container "{1}" on swift'.
format(filename,
self.container))
except Exception, e:
raise SystemExit(_error_codes.get(115).format(
filename, 'Swift', e))
示例6: __init__
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
#.........这里部分代码省略.........
"Checking HTTPS CDN URL Failed %s", sys.exc_info()[1])
def delete_object(self):
"""
Delete the object we created
"""
try:
self.success = True
self.swift_client.delete_object(
self.container['name'], self.object)
self.logger.warning("Object %s Deleted", self.object)
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Object Deletion Failed %s", sys.exc_info()[1])
@monitoring.timeit
def create_cdn_enabled_container(self):
"""
Create a CDN enabled container. We use Swift client to do this except
we use a CDN endpoint
"""
try:
self.success = True
self.container_name = 'cdncheck' + str(time.time())
self.cdn_client.put_container(self.container_name)
self.logger.warning(
"Created New Container %s", self.container_name)
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Create CDN Container Failed %s", sys.exc_info()[1])
@monitoring.timeit
def delete_container(self):
"""
Delete the container we created
"""
try:
self.success = True
self.cdn_containers[self.enabled_container]['cdn_enabled'] = False
# This would take some time to be propagated
# We will keep checking until it's disabled.
self.timer = 0
while self.cdn_containers[
self.enabled_container]['cdn_enabled'] is True:
if self.timer > 90:
break
sleep(1)
self.timer = self.timer + 1
continue
self.logger.warning("Deleting Container: %s", self.container['name'])
示例7: HubicBackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class HubicBackend(duplicity.backend.Backend):
"""
Backend for Swift
"""
def __init__(self, parsed_url):
try:
from swiftclient import Connection
from swiftclient import ClientException
except ImportError:
raise BackendException("This backend requires "
"the python-swiftclient library.")
try:
import requests
except ImportError:
raise BackendException("This backend requires "
"the python-requests library.")
self.session = requests.Session()
self.resp_exc = ClientException
conn_kwargs = {}
# if the user has already authenticated
if os.environ.has_key('HUBIC_ACCESS_TOKEN'):
access_token = os.environ['HUBIC_ACCESS_TOKEN']
else:
if not os.environ.has_key('HUBIC_CLIENT_ID'):
raise BackendException('HUBIC_CLIENT_ID environment variable '
'not set.')
if not os.environ.has_key('HUBIC_CLIENT_SECRET'):
raise BackendException('HUBIC_CLIENT_SECRET environment variable '
'not set.')
if not os.environ.has_key('HUBIC_REFRESH_TOKEN'):
raise BackendException('HUBIC_REFRESH_TOKEN environment variable '
'not set.')
# With these 3 keys, generate an access token
access_token = self.getAccessToken(
client_id = os.environ['HUBIC_CLIENT_ID'],
client_secret = os.environ['HUBIC_CLIENT_SECRET'],
refresh_token = os.environ['HUBIC_REFRESH_TOKEN'],
)
if access_token == None:
raise BackendException('access_token not defined')
# Now obtain hubic openstack credentials
credentials = self.getOpenStackCredentials(access_token=access_token)
if ('endpoint' in credentials) and ('token' in credentials):
conn_kwargs['preauthurl'] = credentials['endpoint']
conn_kwargs['preauthtoken'] = credentials['token']
else:
raise BackendException('Unable to getOpenStackCredentials from access_token')
conn_kwargs['auth_version'] = '1'
self.container = parsed_url.path.lstrip('/')
try:
self.conn = Connection(**conn_kwargs)
self.conn.put_container(self.container)
except Exception, e:
log.FatalError("Connection failed: %s %s"
% (e.__class__.__name__, str(e)),
log.ErrorCode.connection_failed)
示例8: __init__
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class SwiftCheck:
"""
Functional test for Swift - basic workflow as follows:
List containers
List objects in those containers
Update Metadata of the account
Retrieve Metadata of the account
Create a Container
Select that container
Update Metadata of the container
Retrieve Metadata of the container
Create an object in the container
Retrieve the object in the container
Update metadata of the object
Retrieve metadata of the object
Delete object
Delete container.
"""
def __init__(self, logger, exec_time, **kwargs):
self.swift_client = Connection(
user=kwargs['os_username'],
key=kwargs['os_password'],
tenant_name=kwargs['os_tenant_name'],
authurl=kwargs['os_auth_url'],
auth_version="2.0",
os_options={'region_name': kwargs['os_region']}
)
self.service = 'Object Storage'
self.logger = logger
self.exec_time = exec_time
self.zone = kwargs['os_zone']
self.region = kwargs['os_region']
self.failure = None
self.overall_success = True
self.tenant_name = kwargs['os_tenant_name']
@monitoring.timeit
def list_containers(self):
"""
List all the existing containers
"""
try:
self.success = True
self.containers = self.swift_client.get_account()[1]
self.logger.warning("Listing Containers:")
for self.container in self.containers:
self.logger.warning(self.container['name'])
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Listing Swift containers failed %s", sys.exc_info()[1])
@monitoring.timeit
def list_objects(self):
"""
List all the objects contained in each container
"""
try:
self.success = True
self.containers = self.swift_client.get_account()[1]
self.logger.warning("Listing Objects:")
for self.container in self.containers:
try:
for swift_container in self.swift_client.get_container(
self.container['name'])[1]:
self.logger.warning(
self.container['name'] + " " +
swift_container['name'])
except:
pass
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Listing objects failed %s", sys.exc_info()[1])
@monitoring.timeit
def create_container(self):
"""
Create a new container
"""
try:
self.success = True
self.container = 'swiftcheck' + str(time.time())
self.swift_client.put_container(self.container)
self.logger.warning("Created Container %s", self.container)
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class Swift:
def __init__(self, username, password, tenant, auth_url, region):
self.swift_client = Connection(
user=username,
key=password,
tenant_name=tenant,
authurl=auth_url,
auth_version="2.0",
os_options={'region_name': region}
)
# Setup logging
self.logger = logging.getLogger()
self.logger.setLevel(logging.WARNING)
# Allow the logger to write all output to stdout too
self.logger.addHandler(logging.StreamHandler())
def list_containers(self):
try:
self.containers = self.swift_client.get_account()[1]
self.logger.warning("Listing Containers")
for container in self.containers:
self.logger.warning(container['name'])
except Exception:
self.logger.error("Listing Containers Failed")
self.exit(1)
def list_objects(self):
try:
self.logger.warning("Listing Objects")
for container in self.containers:
for swift_container in self.swift_client.get_container(container['name'])[1]:
self.logger.warning(container['name'] + " " + swift_container['name'])
except Exception as e:
self.logger.error('Listing Objects Failed, Got exception: %s' % e)
self.exit(1)
def create_container(self, name):
try:
self.container = name
self.swift_client.put_container(self.container)
self.logger.warning("Created Container %s", self.container)
except Exception:
self.logger.error("Creating Container Failed")
self.exit(1)
def create_object(self, name, contents):
try:
self.object = name
self.swift_client.put_object(self.container, self.object, contents)
self.logger.warning("Created Object %s", self.object)
except Exception:
self.logger.error("Creating Object Failed")
self.exit(1)
def get_container(self):
try:
self.containers = self.swift_client.get_account()[1]
for container in self.containers:
if container['name'] == self.container:
self.logger.warning("Getting Container Succeeded")
return True
self.logger.error("Getting Container Failed")
self.exit(1)
except Exception as e:
self.logger.error('Getting Container Failed: Got exception: ' % e)
self.exit(1)
def get_object(self):
try:
object = self.swift_client.get_object(self.container, self.object)
self.logger.warning("Object Get: %s", object)
except Exception as e:
self.logger.error('Object Get Failed, Got exception: %s' % e)
self.exit(1)
def delete_object(self):
try:
self.swift_client.delete_object(self.container, self.object)
self.logger.warning("Object Deleted")
except Exception as e:
self.logger.error('Object Deletion Failed: Got exception: ' % e)
def delete_container(self):
try:
self.swift_client.delete_container(self.container)
self.logger.warning("Container Deleted")
#.........这里部分代码省略.........
示例10: SwiftBackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class SwiftBackend(duplicity.backend.Backend):
"""
Backend for Swift
"""
def __init__(self, parsed_url):
try:
from swiftclient import Connection
from swiftclient import ClientException
except ImportError:
raise BackendException("This backend requires "
"the python-swiftclient library.")
self.resp_exc = ClientException
conn_kwargs = {}
# if the user has already authenticated
if 'SWIFT_PREAUTHURL' in os.environ and 'SWIFT_PREAUTHTOKEN' in os.environ:
conn_kwargs['preauthurl'] = os.environ['SWIFT_PREAUTHURL']
conn_kwargs['preauthtoken'] = os.environ['SWIFT_PREAUTHTOKEN']
else:
if 'SWIFT_USERNAME' not in os.environ:
raise BackendException('SWIFT_USERNAME environment variable '
'not set.')
if 'SWIFT_PASSWORD' not in os.environ:
raise BackendException('SWIFT_PASSWORD environment variable '
'not set.')
if 'SWIFT_AUTHURL' not in os.environ:
raise BackendException('SWIFT_AUTHURL environment variable '
'not set.')
conn_kwargs['user'] = os.environ['SWIFT_USERNAME']
conn_kwargs['key'] = os.environ['SWIFT_PASSWORD']
conn_kwargs['authurl'] = os.environ['SWIFT_AUTHURL']
if 'SWIFT_AUTHVERSION' in os.environ:
conn_kwargs['auth_version'] = os.environ['SWIFT_AUTHVERSION']
else:
conn_kwargs['auth_version'] = '1'
if 'SWIFT_TENANTNAME' in os.environ:
conn_kwargs['tenant_name'] = os.environ['SWIFT_TENANTNAME']
if 'SWIFT_REGIONNAME' in os.environ:
conn_kwargs['os_options'] = {'region_name': os.environ['SWIFT_REGIONNAME']}
self.container = parsed_url.path.lstrip('/')
container_metadata = None
try:
self.conn = Connection(**conn_kwargs)
container_metadata = self.conn.head_container(self.container)
except ClientException:
pass
except Exception as e:
log.FatalError("Connection failed: %s %s"
% (e.__class__.__name__, str(e)),
log.ErrorCode.connection_failed)
if container_metadata is None:
log.Info("Creating container %s" % self.container)
try:
self.conn.put_container(self.container)
except Exception as e:
log.FatalError("Container creation failed: %s %s"
% (e.__class__.__name__, str(e)),
log.ErrorCode.connection_failed)
def _error_code(self, operation, e):
if isinstance(e, self.resp_exc):
if e.http_status == 404:
return log.ErrorCode.backend_not_found
def _put(self, source_path, remote_filename):
self.conn.put_object(self.container, remote_filename,
file(source_path.name))
def _get(self, remote_filename, local_path):
headers, body = self.conn.get_object(self.container, remote_filename)
with open(local_path.name, 'wb') as f:
for chunk in body:
f.write(chunk)
def _list(self):
headers, objs = self.conn.get_container(self.container, full_listing=True)
return [o['name'] for o in objs]
def _delete(self, filename):
self.conn.delete_object(self.container, filename)
def _query(self, filename):
sobject = self.conn.head_object(self.container, filename)
return {'size': int(sobject['content-length'])}
示例11: PCABackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
#.........这里部分代码省略.........
conn_kwargs['retries'] = 0
self.conn_kwargs = conn_kwargs
# This folds the null prefix and all null parts, which means that:
# //MyContainer/ and //MyContainer are equivalent.
# //MyContainer//My/Prefix/ and //MyContainer/My/Prefix are equivalent.
url_parts = [x for x in parsed_url.path.split('/') if x != '']
self.container = url_parts.pop(0)
if url_parts:
self.prefix = '%s/' % '/'.join(url_parts)
else:
self.prefix = ''
policy = 'PCA'
policy_header = 'X-Storage-Policy'
container_metadata = None
try:
self.conn = Connection(**self.conn_kwargs)
container_metadata = self.conn.head_container(self.container)
except ClientException:
pass
except Exception as e:
log.FatalError("Connection failed: %s %s"
% (e.__class__.__name__, str(e)),
log.ErrorCode.connection_failed)
if container_metadata is None:
log.Info("Creating container %s" % self.container)
try:
headers = dict([[policy_header, policy]])
self.conn.put_container(self.container, headers=headers)
except Exception as e:
log.FatalError("Container creation failed: %s %s"
% (e.__class__.__name__, str(e)),
log.ErrorCode.connection_failed)
elif policy and container_metadata[policy_header.lower()] != policy:
log.FatalError("Container '%s' exists but its storage policy is '%s' not '%s'."
% (self.container, container_metadata[policy_header.lower()], policy))
def _error_code(self, operation, e):
if isinstance(e, self.resp_exc):
if e.http_status == 404:
return log.ErrorCode.backend_not_found
def _put(self, source_path, remote_filename):
self.conn.put_object(self.container, self.prefix + remote_filename,
file(source_path.name))
def _get(self, remote_filename, local_path):
body = self.preprocess_download(remote_filename, 60)
if body:
with open(local_path.name, 'wb') as f:
for chunk in body:
f.write(chunk)
def _list(self):
headers, objs = self.conn.get_container(self.container, full_listing=True, path=self.prefix)
# removes prefix from return values. should check for the prefix ?
return [o['name'][len(self.prefix):] for o in objs]
def _delete(self, filename):
self.conn.delete_object(self.container, self.prefix + filename)
示例12: OptionParser
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
if __name__ == '__main__':
parser = OptionParser(version='%prog 1.0', usage='Usage: %prog -c CONFIG_FILE')
parser.add_option('-c', '--config', dest='config', default='/etc/swilog/swilog.conf', help='Configuration file')
(options, args) = parser.parse_args(sys.argv[1:])
(config, logfiles) = read_configuration(options.config)
# Star the clock here
start_time = time.time()
logger.warn('Initiating log processing.')
conn = Connection(config['swift_auth'], config['swift_user'], config['swift_password'])
cont_name = config['container']
try:
container = conn.head_container(cont_name)
except ClientException as e:
if config['create_container']:
logger.warn('No container by that name - Creating %s.' % cont_name)
container = conn.put_container(cont_name)
else:
logger.fatal('Container %s does not exist. Exiting.' % cont_name)
sys.exit(-1)
# Loop through each declared log file and process
for logfile in logfiles:
log_conf = build_log_config(config, logfile)
processor = LogProcessor(logger, log_conf)
processor.process(conn)
elapsed_time = time.time() - start_time
logger.warn('Processing complete. Total execution %f seconds.' % elapsed_time)
示例13: ConnStorage
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import put_container [as 别名]
class ConnStorage(object):
'''
classdocs
'''
def __init__(self, conf):
'''
根据配置文件初始化连接Swift云存储的客户端,包括认证系统和存储系统。
'''
self.conf = conf
colon = conf['storuser'].find(":")
if colon > 0 :
self.user = conf['storuser'][:colon]
self.tenant = conf['storuser'][colon+1:]
else:
self.user = self.tenant = conf['storuser']
print self.user, self.tenant
self.pawd = conf['storpass']
self.authurl = "http://" + conf['storip'] + ":" + conf['storport'] + "/v2.0/"
# self.keystone = client.Client(username="admin", password="admin",
# tenant_name="admin", auth_url=self.authurl)
self.swift = Connection(authurl=self.authurl, user=self.user, key=self.pawd,
auth_version="2", tenant_name=self.tenant, insecure = True)
# def getTenantList(self):
# items = self.keystone.tenants.list()
# tenantlist=[]
# for item in items:
# tenantlist.append(item.name)
# return tenantlist
#
# def getUserList(self):
# items = self.keystone.users.list()
# userlist = []
# for item in items:
# userlist.append(item.name)
# return userlist
# def addTenant(self):
# tenantlist = self.getTenantList()
# if self.tenant not in tenantlist:
# self.keystone.tenants.create(tenant_name = self.tenant)
# else:
# print "The tenant \"%s\" already existed!" % self.tenant
#
# def addUser(self):
# tenantlist = self.keystone.tenants.list()
# my_tenant = [x for x in tenantlist if x.name == self.tenant][0]
#
# userlist = self.getUserList()
# if self.user not in userlist:
# self.keystone.users.create(name = self.tenant, password = self.pawd,
# tenant_id = my_tenant.id)
# else:
# print "The user \"%s\" already existed under tenant \"%s\"!" % (self.tenant, self.user)
def getContainerList(self):
items = self.swift.get_account()[1]
conlist=[]
for item in items:
conlist.append(item.get('name', item.get('hjc')))
print conlist
return conlist
def getObjectList(self, conName):
items = self.swift.get_container(container=conName)[1]
objlist = []
for item in items:
objlist.append(item.get('name', item.get('hjc')))
return objlist
def upload_file(self, container, objpath):
conlist = self.getContainerList()
if container not in conlist:
try:
self.swift.put_container(container)
except ClientException, err:
msg = ' '.join(str(x) for x in (err.http_status, err.http_reason))
if err.http_response_content:
if msg:
msg += ': '
msg += err.http_response_content[:60]
print 'Error trying to create container %r: %s' % (container, msg)
except Exception, err:
print 'Error trying to create container %r: %s' % (container, err)