本文整理汇总了Python中swiftclient.Connection.head_object方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.head_object方法的具体用法?Python Connection.head_object怎么用?Python Connection.head_object使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类swiftclient.Connection
的用法示例。
在下文中一共展示了Connection.head_object方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SwiftStorage
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import head_object [as 别名]
class SwiftStorage(Storage):
def __init__(self, config):
self._config = config
self._root_path = self._config.storage_path
self._connection = Connection(self._config.storage_auth_url, self._config.storage_account + ':' + self._config.storage_username, self._config.storage_password)
self._container = self._config.storage_container
self._index_lastupdate = None
def _update_index(self):
logger.info("_update_index")
try:
headers = self._connection.head_object(self._container, 'docker-registry.index')
lastupdatestr = headers['last-modified']
if not lastupdatestr:
return
lastupdate = datetime.strptime(lastupdatestr, "%a, %d %b %Y %H:%M:%S %Z")
logger.info('lastupdate: ' + str(lastupdate))
refresh_index = False
if not self._index_lastupdate:
refresh_index = True
elif self._index_lastupdate < lastupdate:
refresh_index = True
if not refresh_index:
return
logger.info("refresh index...")
(headers, data) = self._connection.get_object(self._container, 'docker-registry.index')
(level, temppath) = mkstemp()
tempfile = open(temppath, 'w')
tempfile.write(data)
tempfile.close()
with open(temppath, 'r') as f:
for line in f:
line = line.strip()
if line.startswith("#"):
continue
tokens = line.split('\t')
if len(tokens) < 2:
continue
logger.info("Index: " + str(tokens))
realpath = os.path.join(self._root_path, tokens[0])
if not os.path.exists(realpath):
os.makedirs(realpath)
metafile = open(os.path.join(realpath, '.object'), 'w')
metafile.write(tokens[1])
metafile.close()
os.remove(temppath)
self._index_lastupdate = lastupdate
except ClientException, inst:
if inst.http_status != 404:
raise inst
示例2: SwiftBackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import head_object [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'])}
示例3: __init__
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import head_object [as 别名]
#.........这里部分代码省略.........
self.logger.error("Container not found")
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Selecting a container failed %s", sys.exc_info()[1])
@monitoring.timeit
def get_object(self):
"""
Get the newly created object from the newly created container
"""
try:
self.success = True
object = self.swift_client.get_object(self.container, self.object)
self.logger.warning("Getting Object Succeded: %s", object)
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Getting object failed %s", sys.exc_info()[1])
@monitoring.timeit
def retrieve_metadata_object(self):
"""
Retrieve the metadata of the selected object
"""
try:
self.success = True
object_info = self.swift_client.head_object(
self.container, self.object)
self.logger.warning(
"Getting Object Head succeeded: %s", object_info)
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Retrieving Object Head failed %s", sys.exc_info()[1])
@monitoring.timeit
def retrieve_metadata_account(self):
"""
Retrieve the metadata of the account
"""
try:
self.success = True
account_info = self.swift_client.head_account()
self.logger.warning(
"Getting Account Head succeeded: %s", account_info)
except Exception as e:
self.success, self.overall_success = False, False
self.failure = e
self.logger.error(
"Retrieving Account Head failed %s", sys.exc_info()[1])
@monitoring.timeit
def retrieve_metadata_container(self):
"""
Retrieve the metadata of the container
示例4: PCABackend
# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import head_object [as 别名]
#.........这里部分代码省略.........
# 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)
def _query(self, filename):
sobject = self.conn.head_object(self.container, self.prefix + filename)
return {'size': int(sobject['content-length'])}
def preprocess_download(self, remote_filename, retry_period, wait=True):
body = self.unseal(remote_filename)
try:
if wait:
while not body:
time.sleep(retry_period)
self.conn = self.conn_cls(**self.conn_kwargs)
body = self.unseal(remote_filename)
self.conn.close()
except Exception as e:
log.FatalError("Connection failed: %s %s" % (e.__class__.__name__, str(e)),
log.ErrorCode.connection_failed)
return body
def unseal(self, remote_filename):
try:
_, body = self.conn.get_object(self.container, self.prefix + remote_filename,
resp_chunk_size=1024)
log.Info("File %s was successfully unsealed." % remote_filename)
return body
except self.resp_exc as e:
# The object is sealed but being released.
if e.http_status == 429:
# The retry-after header contains the remaining duration before
# the unsealing operation completes.
duration = int(e.http_response_headers['Retry-After'])
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
eta = "%dh%02dm%02ds" % (h, m, s)
log.Info("File %s is being unsealed, operation ETA is %s." %
(remote_filename, eta))
else:
raise