当前位置: 首页>>代码示例>>Python>>正文


Python Connection.delete_object方法代码示例

本文整理汇总了Python中swiftclient.Connection.delete_object方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.delete_object方法的具体用法?Python Connection.delete_object怎么用?Python Connection.delete_object使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在swiftclient.Connection的用法示例。


在下文中一共展示了Connection.delete_object方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import delete_object [as 别名]

#.........这里部分代码省略.........
    def check_https_url(self):
        """

        Access the object we created using the CDN https url

        """

        try:
            self.success = True
            uri = self.container['x-cdn-ssl-uri'] + self.object
            self.logger.warning("HTTPS URL: %s", uri)

            for x in range(1, 51):
                sleep(10)

                http_client = httplib2.Http(
                    timeout=9, disable_ssl_certificate_validation=True)
                response, content = http_client.request(uri, "GET")

                if response['status'] == '200':
                    self.logger.warning("Checking HTTPS CDN URL Succeeded")

                    return True

            self.logger.error("Checking HTTPS CDN URL Timed Out")
            exit(1)

        except Exception as e:
            self.success, self.overall_success = False, False
            self.failure = e
            self.logger.error(
                "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(
开发者ID:rygy,项目名称:OpenFunc,代码行数:70,代码来源:cdn.py

示例2: __init__

# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import delete_object [as 别名]

#.........这里部分代码省略.........
    def update_metadata_container(self):
        """
        Update the metadata of the container
        """

        try:
            self.success = True
            headers = {"X-Container-Meta-Temp-User": "testuser"}
            self.swift_client.post_container(self.container, headers)
            self.logger.warning(
                "Posting Metadata to Container succeeded: %s", headers)

        except Exception as e:
            self.success, self.overall_success = False, False
            self.failure = e
            self.logger.error(
                "Posting Metadata to Container failed %s", sys.exc_info()[1])

    @monitoring.timeit
    def update_metadata_object(self):
        """
        Update the metadata of the object
        """

        try:
            self.success = True
            headers = {"X-Object-Meta-Temp-User": "testuser"}
            self.swift_client.post_object(self.container, self.object, headers)
            self.logger.warning(
                "Posting Metadata to Object succeeded: %s", headers)

        except Exception as e:
            self.success, self.overall_success = False, False
            self.failure = e
            self.logger.error(
                "Posting Metadata to Object failed %s", sys.exc_info()[1])

    @monitoring.timeit
    def delete_object(self):
        """
        Delete the object created earlier in the process flow
        """

        try:
            self.swift_client.delete_object(self.container, self.object)
            self.logger.warning("Object Deleted")

        except Exception as e:
            self.success, self.overall_success = False, False
            self.failure = e
            self.logger.error(
                "Object Delete failed %s", sys.exc_info()[1])

    @monitoring.timeit
    def delete_container(self):
        """
        Delete the container that was created earlier in the process flow
        """

        try:
            self.swift_client.delete_container(self.container)
            self.logger.warning("Container %s Deleted", self.container)

        except Exception as e:
            self.success, self.overall_success = False, False
            self.failure = e
            self.logger.error(
                "Container Delete Failed %s", sys.exc_info()[1])

    def run(self):
        """
        The driver method that runs all the steps in the process flow
        """

        self.list_containers()
        self.list_objects()

        self.update_metadata_account()
        self.retrieve_metadata_account()

        self.create_container()
        self.get_container()
        self.update_metadata_container()
        self.retrieve_metadata_container()

        self.create_object()
        self.get_object()
        self.update_metadata_object()
        self.retrieve_metadata_object()

        if hasattr(self, 'object'):
            self.delete_object()

        if hasattr(self, 'container'):
            self.delete_container()

        if self.overall_success is True:
            exit(0)
        else:
            exit(1)
开发者ID:rygy,项目名称:OpenFunc,代码行数:104,代码来源:swift.py

示例3: __init__

# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import delete_object [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")
#.........这里部分代码省略.........
开发者ID:aditaa,项目名称:jenkins,代码行数:103,代码来源:swift.py

示例4: __init__

# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import delete_object [as 别名]

#.........这里部分代码省略.........
                    'No CDN containers (cdncheck string) to delete')
                return

            for self.container_name in self.cdn_container_names:

                try:
                    self.objects = self.swift_client.get_container(
                        self.container_name)[1]
                except Exception:
                    self.logger.warning(
                        "Couldn't retrieve objects for %s", self.container_name)
                    self.logger.warning("Deleting the container directly")
                    self.cdn_client.delete_container(self.container_name)
                    continue

                if len(self.objects) == 0:
                    self.logger.warning(
                        'No objects found for %s', self.container_name)
                    self.logger.warning(
                        'Deleting CDN container %s', self.container_name)
                    self.swift_client.delete_container(self.container_name)
                    self.cdn_client.delete_container(self.container_name)
                    continue

                self.object_names = []
                for i in self.swift_client.get_container(self.container_name)[1]:
                    self.object_names.append(str(i['name']))

                self.logger.warning(
                    'Deleting objects for %s', self.container_name)

                for i in self.object_names:
                    self.logger.warning('    Deleting object %s', i)
                    self.swift_client.delete_object(self.container_name, i)

                self.logger.warning(
                    'Deleting CDN container %s', self.container_name)
                self.swift_client.delete_container(self.container_name)
                self.cdn_client.delete_container(self.container_name)

        except Exception as e:
            self.success, self.overall_success = False, False
            self.failure = e
            self.logger.error("<*>delete_cdn_containers Failed %s", e)

    @monitoring.timeit
    def delete_swift_containers(self):
        """
        Description - Delete all containers where name starts with
                        'swiftcheck' and all objects in that container
        """
        try:
            self.success = True
            self.swift_containers = self.swift_client.get_account()[1]
            if len(self.swift_containers) == 0:
                self.logger.warning('No Swift containers to delete')
                return

            self.swift_container_names = []
            for i in self.swift_containers:
                if i['name'].startswith('swiftcheck'):
                    self.swift_container_names.append(str(i['name']))

            for self.container_name in self.swift_container_names:
                self.logger.warning('Container: %s', self.container_name)
                self.objects = self.swift_client.get_container(
开发者ID:rygy,项目名称:OpenFunc,代码行数:70,代码来源:purge_service.py

示例5: SwiftBackend

# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import delete_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'])}
开发者ID:muff1nman,项目名称:duplicity,代码行数:95,代码来源:swiftbackend.py

示例6: PCABackend

# 需要导入模块: from swiftclient import Connection [as 别名]
# 或者: from swiftclient.Connection import delete_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
开发者ID:henrysher,项目名称:duplicity,代码行数:104,代码来源:pcabackend.py


注:本文中的swiftclient.Connection.delete_object方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。