• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python swiftclient.Connection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: SwiftBackend

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"
开发者ID:mmccarry,项目名称:bakthat,代码行数:25,代码来源:backends.py


示例2: get_session

def get_session():
    SWIFT_USER = get_reg_value('HKLM', APP_STORAGE_REG_KEY, 'account')
    SWIFT_PASS = get_reg_value('HKLM', APP_STORAGE_REG_KEY, 'password')
    SWIFT_KEY = get_reg_value('HKLM', APP_STORAGE_REG_KEY, 'key')
    SWIFT_AUTH_URL = get_reg_value('HKLM', APP_STORAGE_REG_KEY, 'auth_url')
    cnx = Connection(SWIFT_AUTH_URL, '%s:%s' % (SWIFT_USER,SWIFT_PASS), SWIFT_KEY)
    cnx.get_auth()
    return cnx
开发者ID:pacopablo,项目名称:anagogic-backup-swift,代码行数:8,代码来源:storage.py


示例3: SwiftStorage

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
开发者ID:yacchin1205,项目名称:docker-registry,代码行数:57,代码来源:swift.py


示例4: SwiftBackend

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)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:53,代码来源:swiftbackend.py


示例5: SwiftBackend

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)
开发者ID:hurlebouc,项目名称:GDuplicity,代码行数:48,代码来源:swiftbackend.py


示例6: __init__

        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))
开发者ID:LisandroSeijo,项目名称:zoort,代码行数:27,代码来源:zoort.py


示例7: __init__

    def __init__(self, logger, exec_time, **kwargs):
        self.keystone_client = keystone_client.Client(
            username=kwargs['os_username'],
            password=kwargs['os_password'],
            tenant_name=kwargs['os_tenant_name'],
            auth_url=kwargs['os_auth_url'])
        self.token = self.keystone_client.auth_ref['token']['id']
        self.tenant_id = self.keystone_client.auth_ref['token']['tenant']['id']
        self.end_points = self.keystone_client.service_catalog.get_endpoints()
        self.region1 = str(self.end_points['hpext:cdn'][0]['region'])
        self.region2 = str(self.end_points['hpext:cdn'][1]['region'])
        self.url1 = str(self.end_points['hpext:cdn'][0]['versionList'])
        self.url1 = self.url1[:-1]
        self.url2 = str(self.end_points['hpext:cdn'][1]['versionList'])
        self.url2 = self.url2[:-1]

        self.END_POINTS = {
            self.region1: self.url1,
            self.region2: self.url2
        }

        self.cdn_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'],
                        'service_type': 'hpext:cdn'})

        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 = 'cdn'
        self.authurl = kwargs['os_auth_url']
        self.logger = logger
        self.exec_time = exec_time
        self.zone = kwargs['os_zone']
        self.failure = None
        self.overall_success = True
        self.region = kwargs['os_region']
        self.tenant_name = kwargs['os_tenant_name']
开发者ID:rygy,项目名称:OpenFunc,代码行数:47,代码来源:cdn.py


示例8: _upload_swift

    def _upload_swift(self):
        tag = str(int(time.time()))

        (tenant, user) = self.cfg["s3user"].split(':')
        auth_url = "http://" + self.cfg["s3host"] + "/v2.0/"

        conn = Connection(auth_url, user, self.cfg["s3pass"],
                          snet=False, tenant_name=tenant, auth_version="2")

        # Not calling conn.put_container() for the same reason of permissions.

        key_name = self.cfg["prefix"] + '/' + "i" + tag
        mimetype = "image/jpeg"
        headers = { "Content-Type": mimetype }
        fp = open(self.cfg["file"], 'rb')
        conn.put_object(self.cfg["bucket"], key_name, fp, headers=headers)
        fp.close()
开发者ID:zaitcev,项目名称:hailcam,代码行数:17,代码来源:hailcamsnap.py


示例9: swift_upload

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
开发者ID:dlf412,项目名称:thunderCopyright,代码行数:18,代码来源:uploader.py


示例10: SwiftStorage

    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))
开发者ID:LisandroSeijo,项目名称:zoort,代码行数:40,代码来源:zoort.py


示例11: __init__

    def __init__(self, auth_url, user_name, key, logger, cache_file_path,
                 object_store_url=None, auth_version="2",
                 os_options=None):
        socket.setdefaulttimeout(30.0)  # timeout set at socket level
        Connection.__init__(self, auth_url, user_name, key, retries=0,
                            os_options=os_options,
                            auth_version=auth_version)
        # needed if keystone-get-token does not work
        self.object_store_url = object_store_url
        self.state = dict()
        for sev in severities:
            for component_name in self.component_names():
                self.state[component_name + sev] = \
                    dict(current_state=component_states.unknown,
                         reason='',
                         metrics={})

        self.latency = dict()
        self.metric_data = []
        self.latency_reset()
        self.logger = logger
        self.cache_file_path = cache_file_path
开发者ID:grze,项目名称:helion-ansible,代码行数:22,代码来源:uptime_mon.py


示例12: __init__

    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())
开发者ID:aditaa,项目名称:jenkins,代码行数:16,代码来源:swift.py


示例13: __init__

    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"],
                              insecure=True)

        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"])
开发者ID:235,项目名称:bakthat,代码行数:18,代码来源:backends.py


示例14: __init__

    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']
开发者ID:rygy,项目名称:OpenFunc,代码行数:18,代码来源:swift.py


示例15: __init__

	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)
开发者ID:hjckevin,项目名称:bak,代码行数:19,代码来源:connStorage.py


示例16: get_access_token

            access_token = get_access_token(
                client_id=client_id,
                client_secret=client_secret,
                refresh_token=refresh_token,
            )
            credentials = get_open_stack_credentials(access_token=access_token)
        except Exception, e:
            lastExc = e
        if lastExc is None:
            break
        time.sleep(5)
    if lastExc is not None: raise lastExc

    conn_kwargs = {}
    if ('endpoint' in credentials) and ('token' in credentials):
        conn_kwargs['preauthurl'] = credentials['endpoint']
        conn_kwargs['preauthtoken'] = credentials['token']
    else:
        print "Asplod"

    conn_kwargs['auth_version'] = '1'

    conn = Connection(**conn_kwargs)
    return conn

if len(sys.argv) < 6:
    print "Wrong args. Use: client_id client_secret refresh_token out_path file"

conn = get_credentials(sys.argv[1], sys.argv[2], sys.argv[3])
conn.put_object(None, sys.argv[4] + os.path.basename(sys.argv[5]), open(sys.argv[5], "rb"))
开发者ID:toddfries,项目名称:python-hubic,代码行数:30,代码来源:upload.py


示例17: PCABackend

class PCABackend(duplicity.backend.Backend):
    """
    Backend for OVH PCA
    """
    def __init__(self, parsed_url):
        duplicity.backend.Backend.__init__(self, parsed_url)

        try:
            from swiftclient import Connection
            from swiftclient import ClientException
        except ImportError as e:
            raise BackendException("""\
PCA backend requires the python-swiftclient library.
Exception: %s""" % str(e))

        self.resp_exc = ClientException
        self.conn_cls = Connection
        conn_kwargs = {}

        # if the user has already authenticated
        if 'PCA_PREAUTHURL' in os.environ and 'PCA_PREAUTHTOKEN' in os.environ:
            conn_kwargs['preauthurl'] = os.environ['PCA_PREAUTHURL']
            conn_kwargs['preauthtoken'] = os.environ['PCA_PREAUTHTOKEN']

        else:
            if 'PCA_USERNAME' not in os.environ:
                raise BackendException('PCA_USERNAME environment variable '
                                       'not set.')

            if 'PCA_PASSWORD' not in os.environ:
                raise BackendException('PCA_PASSWORD environment variable '
                                       'not set.')

            if 'PCA_AUTHURL' not in os.environ:
                raise BackendException('PCA_AUTHURL environment variable '
                                       'not set.')

            conn_kwargs['user'] = os.environ['PCA_USERNAME']
            conn_kwargs['key'] = os.environ['PCA_PASSWORD']
            conn_kwargs['authurl'] = os.environ['PCA_AUTHURL']

        os_options = {}

        if 'PCA_AUTHVERSION' in os.environ:
            conn_kwargs['auth_version'] = os.environ['PCA_AUTHVERSION']
            if os.environ['PCA_AUTHVERSION'] == '3':
                if 'PCA_USER_DOMAIN_NAME' in os.environ:
                    os_options.update({'user_domain_name': os.environ['PCA_USER_DOMAIN_NAME']})
                if 'PCA_USER_DOMAIN_ID' in os.environ:
                    os_options.update({'user_domain_id': os.environ['PCA_USER_DOMAIN_ID']})
                if 'PCA_PROJECT_DOMAIN_NAME' in os.environ:
                    os_options.update({'project_domain_name': os.environ['PCA_PROJECT_DOMAIN_NAME']})
                if 'PCA_PROJECT_DOMAIN_ID' in os.environ:
                    os_options.update({'project_domain_id': os.environ['PCA_PROJECT_DOMAIN_ID']})
                if 'PCA_TENANTNAME' in os.environ:
                    os_options.update({'tenant_name': os.environ['PCA_TENANTNAME']})
                if 'PCA_ENDPOINT_TYPE' in os.environ:
                    os_options.update({'endpoint_type': os.environ['PCA_ENDPOINT_TYPE']})
                if 'PCA_USERID' in os.environ:
                    os_options.update({'user_id': os.environ['PCA_USERID']})
                if 'PCA_TENANTID' in os.environ:
                    os_options.update({'tenant_id': os.environ['PCA_TENANTID']})
                if 'PCA_REGIONNAME' in os.environ:
                    os_options.update({'region_name': os.environ['PCA_REGIONNAME']})

        else:
            conn_kwargs['auth_version'] = '2'
        if 'PCA_TENANTNAME' in os.environ:
            conn_kwargs['tenant_name'] = os.environ['PCA_TENANTNAME']
        if 'PCA_REGIONNAME' in os.environ:
            os_options.update({'region_name': os.environ['PCA_REGIONNAME']})

        conn_kwargs['os_options'] = os_options
        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)),
#.........这里部分代码省略.........
开发者ID:henrysher,项目名称:duplicity,代码行数:101,代码来源:pcabackend.py


示例18: __init__

    def __init__(self, parsed_url):
        duplicity.backend.Backend.__init__(self, parsed_url)

        try:
            from swiftclient import Connection
            from swiftclient import ClientException
        except ImportError as e:
            raise BackendException("""\
PCA backend requires the python-swiftclient library.
Exception: %s""" % str(e))

        self.resp_exc = ClientException
        self.conn_cls = Connection
        conn_kwargs = {}

        # if the user has already authenticated
        if 'PCA_PREAUTHURL' in os.environ and 'PCA_PREAUTHTOKEN' in os.environ:
            conn_kwargs['preauthurl'] = os.environ['PCA_PREAUTHURL']
            conn_kwargs['preauthtoken'] = os.environ['PCA_PREAUTHTOKEN']

        else:
            if 'PCA_USERNAME' not in os.environ:
                raise BackendException('PCA_USERNAME environment variable '
                                       'not set.')

            if 'PCA_PASSWORD' not in os.environ:
                raise BackendException('PCA_PASSWORD environment variable '
                                       'not set.')

            if 'PCA_AUTHURL' not in os.environ:
                raise BackendException('PCA_AUTHURL environment variable '
                                       'not set.')

            conn_kwargs['user'] = os.environ['PCA_USERNAME']
            conn_kwargs['key'] = os.environ['PCA_PASSWORD']
            conn_kwargs['authurl'] = os.environ['PCA_AUTHURL']

        os_options = {}

        if 'PCA_AUTHVERSION' in os.environ:
            conn_kwargs['auth_version'] = os.environ['PCA_AUTHVERSION']
            if os.environ['PCA_AUTHVERSION'] == '3':
                if 'PCA_USER_DOMAIN_NAME' in os.environ:
                    os_options.update({'user_domain_name': os.environ['PCA_USER_DOMAIN_NAME']})
                if 'PCA_USER_DOMAIN_ID' in os.environ:
                    os_options.update({'user_domain_id': os.environ['PCA_USER_DOMAIN_ID']})
                if 'PCA_PROJECT_DOMAIN_NAME' in os.environ:
                    os_options.update({'project_domain_name': os.environ['PCA_PROJECT_DOMAIN_NAME']})
                if 'PCA_PROJECT_DOMAIN_ID' in os.environ:
                    os_options.update({'project_domain_id': os.environ['PCA_PROJECT_DOMAIN_ID']})
                if 'PCA_TENANTNAME' in os.environ:
                    os_options.update({'tenant_name': os.environ['PCA_TENANTNAME']})
                if 'PCA_ENDPOINT_TYPE' in os.environ:
                    os_options.update({'endpoint_type': os.environ['PCA_ENDPOINT_TYPE']})
                if 'PCA_USERID' in os.environ:
                    os_options.update({'user_id': os.environ['PCA_USERID']})
                if 'PCA_TENANTID' in os.environ:
                    os_options.update({'tenant_id': os.environ['PCA_TENANTID']})
                if 'PCA_REGIONNAME' in os.environ:
                    os_options.update({'region_name': os.environ['PCA_REGIONNAME']})

        else:
            conn_kwargs['auth_version'] = '2'
        if 'PCA_TENANTNAME' in os.environ:
            conn_kwargs['tenant_name'] = os.environ['PCA_TENANTNAME']
        if 'PCA_REGIONNAME' in os.environ:
            os_options.update({'region_name': os.environ['PCA_REGIONNAME']})

        conn_kwargs['os_options'] = os_options
        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)
#.........这里部分代码省略.........
开发者ID:henrysher,项目名称:duplicity,代码行数:101,代码来源:pcabackend.py


示例19: __init__

class PurgeCheck:
    """
        Description - Purge left over elements created by each service.
                      Service is selected and then specific deletes for
                      that service are executed.
        Basic workflow

        if cdn
            delete_cdn_containers
        if cinder
            delete_snapshots
            delete_volume
        if domains
            delete_domains
        if keystone
            pass
        if libra
            delete_lb
        if neutron
            delete_floating
            delete_port
            delete_router
            delete_subnet
            delete_network
        if nova
            delete_instance
            delete_floating
            delete_keypair
        if swift
            delete_swift_containers
        if trove
            delete_db
    """

    def __init__(self, logger, exec_time, **kwargs):
        self.neutron_client = neutron_client.Client(
            username=kwargs['os_username'],
            password=kwargs['os_password'],
            tenant_name=kwargs['os_tenant_name'],
            auth_url=kwargs['os_auth_url'],
            region_name=kwargs['os_region']
        )
        self.nova_client = nova_client.Client(
            kwargs['os_username'],
            kwargs['os_password'],
            kwargs['os_tenant_name'],
            kwargs['os_auth_url'],
            region_name=kwargs['os_region']
        )
        self.cinder_client = cinder_client.Client(
            kwargs['os_username'],
            kwargs['os_password'],
            kwargs['os_tenant_name'],
            kwargs['os_auth_url'],
            region_name=kwargs['os_region'],
            service_type="volume"
        )
        self.client = client.Client(
            kwargs['os_username'],
            kwargs['os_password'],
            kwargs['os_tenant_name'],
            kwargs['os_auth_url'],
            region_name=kwargs['os_region'],
        )
        self.keystone_client = keystone_client.Client(
            username=kwargs['os_username'],
            password=kwargs['os_password'],
            tenant_name=kwargs['os_tenant_name'],
            auth_url=kwargs['os_auth_url']
        )

        self.designate_client = Designate(
            auth_url=kwargs['os_auth_url'],
            username=kwargs['os_username'],
            password=kwargs['os_password'],
            tenant_name=kwargs['os_tenant_name'],
            region_name=kwargs['os_region'],
            service_type='hpext:dns'
        )

        self.swift_cdn_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'],
                        'service_type': 'hpext:cdn'}
        )

        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.cdn_client = cdn.Client(
#.........这里部分代码省略.........
开发者ID:rygy,项目名称:OpenFunc,代码行数:101,代码来源:purge_service.py


示例20: __init__

    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)
开发者ID:python-consulting,项目名称:utilities,代码行数:64,代码来源:hubicbackend.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python client.delete_container函数代码示例发布时间:2022-05-27
下一篇:
Python swiftclient.put_object函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap