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


Python AstakosClient.get_service_endpoints方法代码示例

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


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

示例1: authenticate

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
    def authenticate(self, authentication=None):
        """

        :param authentication:
        :return:
        """
        if self.__cyclades is not None:
            return True
        try:
            authcl = AstakosClient(authentication['URL'], authentication['TOKEN'])
            authcl.authenticate()
            self.__cyclades = CycladesClient(authcl.get_service_endpoints('compute')['publicURL'],
                                             authentication['TOKEN'])
            self.__network_client = CycladesNetworkClient(authcl.get_service_endpoints('network')['publicURL'],
                                                          authentication['TOKEN'])
        except ClientError:
            stderr.write('Connector initialization failed')
            return False
        return True
开发者ID:vpapaioannou,项目名称:IReS-Platform,代码行数:21,代码来源:okeanos.py

示例2: Image

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
class Image(livetest.Generic):
    def setUp(self):
        self.now = time.mktime(time.gmtime())
        self.cloud = 'cloud.%s' % self['testcloud']
        aurl, self.token = self[self.cloud, 'url'], self[self.cloud, 'token']
        self.auth_base = AstakosCachedClient(aurl, self.token)
        self.imgname = 'img_%s' % self.now
        url = self.auth_base.get_service_endpoints('image')['publicURL']
        self.token = self.auth_base.token
        self.client = ImageClient(url, self.token)
        cyclades_url = self.auth_base.get_service_endpoints(
            'compute')['publicURL']
        self.cyclades = CycladesClient(cyclades_url, self.token)
        self._imglist = {}
        self._imgdetails = {}

    def test_000(self):
        self._prepare_img()
        super(self.__class__, self).test_000()

    def _prepare_img(self):
        f = open(self['image', 'local_path'], 'rb')
        (token, uuid) = (self.token, self.auth_base.user_term('id'))
        purl = self.auth_base.get_service_endpoints(
            'object-store')['publicURL']
        from kamaki.clients.pithos import PithosClient
        self.pithcli = PithosClient(purl, token, uuid)
        cont = 'cont_%s' % self.now
        self.pithcli.container = cont
        self.obj = 'obj_%s' % self.now
        print('\t- Create container %s on Pithos server' % cont)
        self.pithcli.container_put()
        self.location = 'pithos://%s/%s/%s' % (uuid, cont, self.obj)
        print('\t- Upload an image at %s...\n' % self.location)
        self.pithcli.upload_object(self.obj, f)
        print('\t- ok')
        f.close()

        r = self.client.register(
            self.imgname, self.location, params=dict(is_public=True))
        self._imglist[self.imgname] = dict(
            name=r['name'], id=r['id'])
        self._imgdetails[self.imgname] = r

    def tearDown(self):
        for img in self._imglist.values():
            print('\tDeleting image %s' % img['id'])
            self.cyclades.delete_image(img['id'])
        if hasattr(self, 'pithcli'):
            print('\tDeleting container %s' % self.pithcli.container)
            try:
                self.pithcli.del_container(delimiter='/')
                self.pithcli.purge_container()
            except ClientError:
                pass

    def _get_img_by_name(self, name):
        r = self.cyclades.list_images()
        for img in r:
            if img['name'] == name:
                return img
        return None

    def test_list_public(self):
        """Test list_public"""
        self._test_list_public()

    def _test_list_public(self):
        r = self.client.list_public()
        r0 = self.client.list_public(order='-')
        self.assertTrue(len(r) > 0)
        for img in r:
            for term in (
                    'status',
                    'name',
                    'container_format',
                    'disk_format',
                    'id',
                    'size'):
                self.assertTrue(term in img)
        self.assertTrue(r, r0)
        r0.reverse()
        for i, img in enumerate(r):
            self.assert_dicts_are_equal(img, r0[i])
        r1 = self.client.list_public(detail=True)
        for img in r1:
            for term in (
                    'status',
                    'name',
                    'checksum',
                    'created_at',
                    'disk_format',
                    'updated_at',
                    'id',
                    'location',
                    'container_format',
                    'owner',
                    'is_public',
                    'deleted_at',
                    'properties',
#.........这里部分代码省略.........
开发者ID:Erethon,项目名称:kamaki,代码行数:103,代码来源:image.py

示例3: SynnefoCI

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
class SynnefoCI(object):
    """SynnefoCI python class"""

    def __init__(self, config_file=None, build_id=None, cloud=None):
        """ Initialize SynnefoCI python class

        Setup logger, local_dir, config and kamaki
        """
        # Setup logger
        self.logger = logging.getLogger('synnefo-ci')
        self.logger.setLevel(logging.DEBUG)

        handler1 = logging.StreamHandler(sys.stdout)
        handler1.setLevel(logging.DEBUG)
        handler1.addFilter(_InfoFilter())
        handler1.setFormatter(_MyFormatter())
        handler2 = logging.StreamHandler(sys.stderr)
        handler2.setLevel(logging.WARNING)
        handler2.setFormatter(_MyFormatter())

        self.logger.addHandler(handler1)
        self.logger.addHandler(handler2)

        # Get our local dir
        self.ci_dir = os.path.dirname(os.path.abspath(__file__))
        self.repo_dir = os.path.dirname(self.ci_dir)

        # Read config file
        if config_file is None:
            config_file = os.path.join(self.ci_dir, DEFAULT_CONFIG_FILE)
        config_file = os.path.abspath(config_file)
        self.config = ConfigParser()
        self.config.optionxform = str
        self.config.read(config_file)

        # Read temporary_config file
        self.temp_config_file = \
            os.path.expanduser(self.config.get('Global', 'temporary_config'))
        self.temp_config = ConfigParser()
        self.temp_config.optionxform = str
        self.temp_config.read(self.temp_config_file)
        self.build_id = build_id
        self.logger.info("Will use \"%s\" as build id" % _green(self.build_id))

        # Set kamaki cloud
        if cloud is not None:
            self.kamaki_cloud = cloud
        elif self.config.has_option("Deployment", "kamaki_cloud"):
            kamaki_cloud = self.config.get("Deployment", "kamaki_cloud")
            if kamaki_cloud == "":
                self.kamaki_cloud = None
        else:
            self.kamaki_cloud = None

        # Initialize variables
        self.fabric_installed = False
        self.kamaki_installed = False
        self.cyclades_client = None
        self.compute_client = None
        self.image_client = None
        self.astakos_client = None

    def setup_kamaki(self):
        """Initialize kamaki

        Setup cyclades_client, image_client and compute_client
        """

        config = kamaki_config.Config()
        if self.kamaki_cloud is None:
            self.kamaki_cloud = config.get_global("default_cloud")

        self.logger.info("Setup kamaki client, using cloud '%s'.." %
                         self.kamaki_cloud)
        auth_url = config.get_cloud(self.kamaki_cloud, "url")
        self.logger.debug("Authentication URL is %s" % _green(auth_url))
        token = config.get_cloud(self.kamaki_cloud, "token")
        #self.logger.debug("Token is %s" % _green(token))

        self.astakos_client = AstakosClient(auth_url, token)

        cyclades_url = \
            self.astakos_client.get_service_endpoints('compute')['publicURL']
        self.logger.debug("Cyclades API url is %s" % _green(cyclades_url))
        self.cyclades_client = CycladesClient(cyclades_url, token)
        self.cyclades_client.CONNECTION_RETRY_LIMIT = 2

        image_url = \
            self.astakos_client.get_service_endpoints('image')['publicURL']
        self.logger.debug("Images API url is %s" % _green(image_url))
        self.image_client = ImageClient(cyclades_url, token)
        self.image_client.CONNECTION_RETRY_LIMIT = 2

        compute_url = \
            self.astakos_client.get_service_endpoints('compute')['publicURL']
        self.logger.debug("Compute API url is %s" % _green(compute_url))
        self.compute_client = ComputeClient(compute_url, token)
        self.compute_client.CONNECTION_RETRY_LIMIT = 2

    def _wait_transition(self, server_id, current_status, new_status):
#.........这里部分代码省略.........
开发者ID:cstavr,项目名称:synnefo,代码行数:103,代码来源:utils.py

示例4: Cyclades

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
class Cyclades(livetest.Generic):
    """Set up a Cyclades test"""
    def setUp(self):
        print
        with open(self['cmpimage', 'details']) as f:
            self.img_details = eval(f.read())
        self.img = self.img_details['id']
        with open(self['flavor', 'details']) as f:
            self._flavor_details = eval(f.read())
        self.PROFILES = ('ENABLED', 'DISABLED', 'PROTECTED')

        self.servers = {}
        self.now = time.mktime(time.gmtime())
        self.servname1 = 'serv' + unicode(self.now)
        self.servname2 = self.servname1 + '_v2'
        self.servname1 += '_v1'
        self.flavorid = self._flavor_details['id']
        #servers have to be created at the begining...
        self.networks = {}
        self.netname1 = 'net' + unicode(self.now)
        self.netname2 = 'net' + unicode(self.now) + '_v2'

        self.cloud = 'cloud.%s' % self['testcloud']
        aurl, self.token = self[self.cloud, 'url'], self[self.cloud, 'token']
        self.auth_base = AstakosClient(aurl, self.token)
        curl = self.auth_base.get_service_endpoints('compute')['publicURL']
        self.client = CycladesClient(curl, self.token)

    def tearDown(self):
        """Destoy servers used in testing"""
        for net in self.networks.keys():
            self._delete_network(net)
        for server in self.servers.values():
            self._delete_server(server['id'])
            print('DEL VM %s (%s)' % (server['id'], server['name']))

    def test_000(self):
        "Prepare a full Cyclades test scenario"
        self.server1 = self._create_server(
            self.servname1, self.flavorid, self.img)
        self.server2 = self._create_server(
            self.servname2, self.flavorid, self.img)
        super(self.__class__, self).test_000()

    def _create_server(self, servername, flavorid, imageid, personality=None):
        server = self.client.create_server(
            servername, flavorid, imageid, personality=personality)
        print('CREATE VM %s (%s)' % (server['id'], server['name']))
        self.servers[servername] = server
        return server

    def _delete_server(self, servid):
        try:
            current_state = self.client.get_server_details(servid)
            current_state = current_state['status']
            if current_state == 'DELETED':
                return
            self.client.delete_server(servid)
            self._wait_for_status(servid, current_state)
            self.client.delete_server(servid)
        except:
            return

    def _create_network(self, netname, **kwargs):
        net = self.client.create_network(netname, **kwargs)
        self.networks[net['id']] = net
        return net

    def _delete_network(self, netid):
        if not netid in self.networks:
            return None
        print('Disconnect nics of network %s' % netid)
        self.client.disconnect_network_nics(netid)

        def netwait(wait):
            try:
                self.client.delete_network(netid)
            except ClientError:
                time.sleep(wait)
        self.do_with_progress_bar(
            netwait,
            'Delete network %s' % netid,
            self._waits[:7])
        return self.networks.pop(netid)

    def _wait_for_network(self, netid, status):

        def netwait(wait):
            r = self.client.get_network_details(netid)
            if r['status'] == status:
                return
            time.sleep(wait)
        self.do_with_progress_bar(
            netwait,
            'Wait network %s to reach status %s' % (netid, status),
            self._waits[:5])

    def _wait_for_nic(self, netid, servid, in_creation=True):
        self._wait_for_network(netid, 'ACTIVE')

#.........这里部分代码省略.........
开发者ID:Erethon,项目名称:kamaki,代码行数:103,代码来源:cyclades.py

示例5: AstakosClient

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
__author__ = 'cmantas'
import psycopg2
from kamaki.clients.astakos import AstakosClient
from kamaki.clients.cyclades import CycladesClient
from logging import getLogger, ERROR


# init synneffo  stuff

AUTHENTICATION_URL="https://accounts.okeanos.grnet.gr/identity/v2.0"
TOKEN="hYDRO-FEV5d8wFxpOID-DF3_FWhsuD8dvTdbEX2qQRQ"
synnefo_user = AstakosClient(AUTHENTICATION_URL, TOKEN)
synnefo_user.logger.setLevel(ERROR)
getLogger().setLevel(ERROR)
cyclades_endpoints = synnefo_user.get_service_endpoints('compute')
CYCLADES_URL = cyclades_endpoints['publicURL']
cyclades_client = CycladesClient(CYCLADES_URL, TOKEN)

# connect to db

db = psycopg2.connect(host="127.0.0.1", user="celaruser", password="celar-user", database="celardb")
cursor = db.cursor()


#clear all old values from the DB
cursor.execute("DELETE FROM \"RESOURCE_TYPE\" WHERE TRUE")
cursor.execute("DELETE FROM \"SPECS\" WHERE TRUE")
cursor.execute("DELETE FROM \"PROVIDED_RESOURCE\" WHERE TRUE")


# add 'VM_FLAVOR' entry on the RESOURCE_TYPE table
开发者ID:cmantas,项目名称:celar_db_client,代码行数:33,代码来源:load_provided_resources.py

示例6: AstakosClient

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
class AstakosClient(TestCase):

    cached = False

    def assert_dicts_are_equal(self, d1, d2):
        for k, v in d1.items():
            self.assertTrue(k in d2)
            if isinstance(v, dict):
                self.assert_dicts_are_equal(v, d2[k])
            else:
                self.assertEqual(unicode(v), unicode(d2[k]))

    def setUp(self):
        self.url = 'https://astakos.example.com'
        self.token = '[email protected]=='
        from kamaki.clients.astakos import AstakosClient as AC
        self.client = AC(self.url, self.token)

    def tearDown(self):
        FR.json = example

    @patch('%s.LoggedAstakosClient.__init__' % astakos_pkg, return_value=None)
    @patch(
        '%s.LoggedAstakosClient.get_endpoints' % astakos_pkg,
        return_value=example)
    def _authenticate(self, get_endpoints, sac):
        r = self.client.authenticate()
        self.assertEqual(
            sac.mock_calls[-1], call(self.token, self.url,
                logger=getLogger('astakosclient')))
        self.assertEqual(get_endpoints.mock_calls[-1], call())
        return r

    def test_authenticate(self):
        r = self._authenticate()
        self.assert_dicts_are_equal(r, example)
        uuid = example['access']['user']['id']
        self.assert_dicts_are_equal(self.client._uuids, {self.token: uuid})
        self.assert_dicts_are_equal(self.client._cache, {uuid: r})
        from astakosclient import AstakosClient as SAC
        self.assertTrue(isinstance(self.client._astakos[uuid], SAC))
        self.assert_dicts_are_equal(self.client._uuids2usernames, {uuid: {}})
        self.assert_dicts_are_equal(self.client._usernames2uuids, {uuid: {}})

    def test_get_client(self):
        if not self.cached:
            self._authenticate()
        from astakosclient import AstakosClient as SNFAC
        self.assertTrue(self.client.get_client(), SNFAC)

    def test_get_token(self):
        self._authenticate()
        uuid = self.client._uuids.values()[0]
        self.assertEqual(self.client.get_token(uuid), self.token)

    def test_get_services(self):
        if not self.cached:
            self._authenticate()
        slist = self.client.get_services()
        self.assertEqual(slist, example['access']['serviceCatalog'])

    def test_get_service_details(self):
        if not self.cached:
            self._authenticate()
        stype = '#FAIL'
        self.assertRaises(ClientError, self.client.get_service_details, stype)
        stype = 'compute'
        expected = [s for s in example['access']['serviceCatalog'] if (
            s['type'] == stype)]
        self.assert_dicts_are_equal(
            self.client.get_service_details(stype), expected[0])

    def test_get_service_endpoints(self):
        if not self.cached:
            self._authenticate()
        stype, version = 'compute', 'V2'
        self.assertRaises(
            ClientError, self.client.get_service_endpoints, stype)
        expected = [s for s in example['access']['serviceCatalog'] if (
            s['type'] == stype)]
        expected = [e for e in expected[0]['endpoints'] if (
            e['versionId'] == version.lower())]
        self.assert_dicts_are_equal(
            self.client.get_service_endpoints(stype, version), expected[0])

    def test_user_info(self):
        if not self.cached:
            self._authenticate()
        self.assertTrue(set(example['access']['user'].keys()).issubset(
            self.client.user_info().keys()))

    def test_item(self):
        if not self.cached:
            self._authenticate()
        for term, val in example['access']['user'].items():
            self.assertEqual(self.client.term(term, self.token), val)
        self.assertTrue(
            example['access']['user']['email'][0] in self.client.term('email'))

    def test_list_users(self):
#.........这里部分代码省略.........
开发者ID:Erethon,项目名称:kamaki,代码行数:103,代码来源:test.py

示例7: main

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
def main():
    """Entry point for icaas-monitord"""

    args = get_args()

    manifest = read_manifest(args.manifest)

    if 'status' not in manifest['service']:
        sys.stderr.write('"status" is missing from the service section of the '
                         'manifest')
        sys.exit(3)

    if 'insecure' in manifest and manifest['insecure'].lower() == 'true':
        verify = False
    else:
        verify = True

    report = Report(manifest['service']['status'], verify=verify,
                    log=sys.stderr)

    def missing_key(key, section):
        """missing key message"""
        return "`%s' is missing from the `%s' section of the manifest" % \
            (key, section)

    # Validate the manifest
    for key in 'url', 'token', 'log', 'status':
        if key not in manifest['service']:
            report.error(missing_key(key, 'service'))
            sys.exit(3)

    for key in 'url', 'name', 'object':
        if key not in manifest['image']:
            report.error(missing_key(key, 'image'))
            sys.exit(3)

    service = manifest['service']

    try:
        container, logname = service['log'].split('/', 1)
    except ValueError:
        report.error('Incorrect format for log entry in manifest file')

    # Use the systems certificates
    https.patch_with_certs(CERTS)

    account = AstakosClient(service['url'], service['token'])
    try:
        account.authenticate()
    except AstakosClientError as err:
        report.error("Astakos: %s" % err)
        sys.exit(3)

    pithos = PithosClient(
        account.get_service_endpoints('object-store')['publicURL'],
        account.token, account.user_info['id'], container)

    if args.daemonize:
        daemon_context = daemon.DaemonContext(stdin=sys.stdin,
                                              stdout=sys.stdout,
                                              stderr=sys.stderr)
        daemon_context.open()

    with open(PID, 'w') as pid:
        pid.write("%d\n" % os.getpid())

    try:
        # Export manifest to environment variables
        for section in manifest:
            for key, value in manifest[section].items():
                name = "ICAAS_%s_%s" % (section.upper(), key.upper())
                os.environ[name] = value

        # Use SIGHUP to unblock from the sleep if necessary
        signal.signal(signal.SIGHUP, lambda x, y: None)

        if 'ICAAS_MONITOR_SIGSTOP' in os.environ:
            # Tell service supervisor that we are ready.
            syslog.syslog(
                syslog.LOG_NOTICE, "Stopping with SIGSTOP as the "
                "environment variable ICAAS_MONITOR_SIGSTOP is defined")
            os.kill(os.getpid(), signal.SIGSTOP)
            del os.environ['ICAAS_MONITOR_SIGSTOP']

        if do_main_loop(args.interval, pithos, logname):
            report.success()
        else:
            report.error("Image creation failed. Check the log for more info")
    finally:
        os.unlink(PID)
开发者ID:pombredanne,项目名称:icaas-agent,代码行数:92,代码来源:monitord.py

示例8: Astakos

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
class Astakos(livetest.Generic):
    def setUp(self):
        self.cloud = 'cloud.%s' % self['testcloud']
        self.client = AstakosClient(
            self[self.cloud, 'url'], self[self.cloud, 'token'])
        with open(self['astakos', 'details']) as f:
            self._astakos_details = eval(f.read())

    def test_authenticate(self):
        self._test_0010_authenticate()

    def _test_0010_authenticate(self):
        r = self.client.authenticate()
        self.assert_dicts_are_equal(r, self._astakos_details)

    def test_get_services(self):
        self._test_0020_get_services()

    def _test_0020_get_services(self):
        for args in (tuple(), (self[self.cloud, 'token'],)):
            r = self.client.get_services(*args)
            services = self._astakos_details['access']['serviceCatalog']
            self.assertEqual(len(services), len(r))
            for i, service in enumerate(services):
                self.assert_dicts_are_equal(r[i], service)
        self.assertRaises(ClientError, self.client.get_services, 'wrong_token')

    def test_get_service_details(self):
        self._test_0020_get_service_details()

    def _test_0020_get_service_details(self):
        parsed_services = dict()
        for args in product(
                self._astakos_details['access']['serviceCatalog'],
                ([tuple(), (self[self.cloud, 'token'],)])):
            service = args[0]
            if service['type'] in parsed_services:
                continue
            r = self.client.get_service_details(service['type'], *args[1])
            self.assert_dicts_are_equal(r, service)
            parsed_services[service['type']] = True
        self.assertRaises(
            ClientError, self.client.get_service_details, 'wrong_token')

    def test_get_service_endpoints(self):
        self._test_0020_get_service_endpoints()

    def _test_0020_get_service_endpoints(self):
        parsed_services = dict()
        for args in product(
                self._astakos_details['access']['serviceCatalog'],
                ([], [self[self.cloud, 'token']])):
            service = args[0]
            if service['type'] in parsed_services:
                continue
            for endpoint, with_id in product(
                    service['endpoints'], (True, False)):
                vid = endpoint['versionId'] if (
                    with_id and endpoint['versionId']) else None
                end_args = [service['type'], vid] + args[1]
                r = self.client.get_service_endpoints(*end_args)
                self.assert_dicts_are_equal(r, endpoint)
            parsed_services[service['type']] = True
        self.assertRaises(
            ClientError, self.client.get_service_endpoints, 'wrong_token')

    def test_user_info(self):
        self._test_0020_user_info()

    def _test_0020_user_info(self):
        self.assertTrue(set([
            'roles',
            'name',
            'id']).issubset(self.client.user_info().keys()))

    def test_get(self):
        self._test_0020_get()

    def _test_0020_get(self):
        for term in ('id', 'name'):
            self.assertEqual(
                self.client.term(term, self[self.cloud, 'token']),
                self['astakos', term] or '')

    def test_list_users(self):
        self.client.authenticate()
        self._test_0020_list_users()

    def _test_0020_list_users(self):
        terms = set(['name', 'id'])
        uuid = 0
        for r in self.client.list_users():
            self.assertTrue(terms.issubset(r.keys()))
            self.assertTrue(uuid != r['id'] if uuid else True)
            uuid = r['id']
开发者ID:Erethon,项目名称:kamaki,代码行数:97,代码来源:astakos.py

示例9: main

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
def main():
    #authenticate to Astakos
    print"---------------------------------------------------"
    print"******* Authenticating to Astakos******************"
    print"---------------------------------------------------"
    try:
        my_astakos_client = AstakosClient(AUTHENTICATION_URL,
                                          TOKEN)
        my_accountData = my_astakos_client.authenticate()
        ACCOUNT_UUID = my_accountData['access']['user']['id']
        print "Status: Authenticated"
    except ClientError:
        print"Failed to authenticate user token"

    print"\n"
    print"---------------------------------------------------"
    print"**********Getting Endpoints for pithos*************"
    print"---------------------------------------------------"
    #get endpoint url
    try:
        endpoints = my_astakos_client.get_service_endpoints('object-store')
        PITHOS_URL = endpoints['publicURL']
        print "The public URL:", PITHOS_URL
    except ClientError:
        print "Failed to get endpoints for pithos"

    print"\n"
    print"---------------------------------------------------"
    print"**********Authenticating to Pithos*****************"
    print"---------------------------------------------------"
    #Initialize pithos client
    try:
        pithos = PithosClient(PITHOS_URL, TOKEN)
        pithos.account = ACCOUNT_UUID
        pithos.container = ''
    except ClientError:
        print "Failed to initialize Pithos+ client"

    print"\n"
    print"---------------------------------------------------"
    print"**********LIST ALL CONTAINERS IN YOUR ACCOUNT******"
    print"---------------------------------------------------"
    #list all containers
    try:
        container_list = pithos.list_containers()
        containers = parse_containers(container_list)
        ContNums = len(containers)
        print "The number of Containers in your account:", ContNums
        print "The containers are"
        print ','.join(containers)
    except ClientError:
        print"Error in container list"

    print"\n"
    print"---------------------------------------------------"
    print"******LIST OBJECTS OF A FOLDER IN A CONTAINER******"
    print"---------------------------------------------------"
    #list all containers
    try:
        print_container_objects(pithos, YOUR_CONTAINER,
                              prefixName=YOUR_FOLDER_PATH)
    except ClientError:
        print"Error in listing folder objects"

    print"\n"
    print"---------------------------------------------------"
    print"**********Print objects for all containers*********"
    print"---------------------------------------------------"

    try:
        for i in range(len(containers)):
            print_container_objects(pithos, containers[i])
    except ClientError as e:
        print('Error: %s' % e)
        if e.status:
            print('- error code: %s' % e.status)
        if e.details:
            for detail in e.details:
                print('- %s' % detail)

    #  Create and set a different container than pithos
    print "Create a new container - my container"
    CONTAINER = 'my container'
    pithos.create_container(CONTAINER)
    pithos.container = CONTAINER

    print"\n"
    print"---------------------------------------------------"
    print"**********UPLOAD AND DOWNLOAD**********************"
    print"---------------------------------------------------"
    """
    B. UPLOAD AND DOWNLOAD
    """
    print "Upload a small file to pithos"
    #  Upload a small file
    print './test/'+SMALLFILE
    with open('./test/'+SMALLFILE) as f:
        pithos.upload_object(SMALLFILE, f)

    print "Download a small file from pithos and store to string"
#.........这里部分代码省略.........
开发者ID:themiszamani,项目名称:kamaki-examples,代码行数:103,代码来源:pithos.py

示例10: Pithos

# 需要导入模块: from kamaki.clients.astakos import AstakosClient [as 别名]
# 或者: from kamaki.clients.astakos.AstakosClient import get_service_endpoints [as 别名]
class Pithos(livetest.Generic):

    files = []

    def setUp(self):
        self.cloud = 'cloud.%s' % self['testcloud']
        aurl, self.token = self[self.cloud, 'url'], self[self.cloud, 'token']
        self.auth_base = AstakosClient(aurl, self.token)
        purl = self.auth_base.get_service_endpoints(
            'object-store')['publicURL']
        self.uuid = self.auth_base.user_term('id')
        self.client = PithosClient(purl, self.token, self.uuid)

        self.now = time.mktime(time.gmtime())
        self.now_unformated = datetime.datetime.utcnow()
        self._init_data()

        """Prepare an object to be shared - also its container"""
        self.client.container = self.c1
        self.client.object_post(
            'test',
            update=True,
            permissions={'read': [self.client.account]})

        self.create_remote_object(self.c1, 'another.test')

    def _init_data(self):
        self.c1 = 'c1_' + unicode(self.now)
        self.c2 = 'c2_' + unicode(self.now)
        self.c3 = 'c3_' + unicode(self.now)
        try:
            self.client.create_container(self.c2)
        except ClientError:
            pass
        try:
            self.client.create_container(self.c1)
        except ClientError:
            pass
        try:
            self.client.create_container(self.c3)
        except ClientError:
            pass

        self.create_remote_object(self.c1, 'test')
        self.create_remote_object(self.c2, 'test')
        self.create_remote_object(self.c1, 'test1')
        self.create_remote_object(self.c2, 'test1')

    def create_remote_object(self, container, obj):
        self.client.container = container
        self.client.object_put(
            obj,
            content_type='application/octet-stream',
            data='file %s that lives in %s' % (obj, container),
            metadata={'incontainer': container})

    def forceDeleteContainer(self, container):
        self.client.container = container
        try:
            r = self.client.list_objects()
        except ClientError:
            return
        for obj in r:
            name = obj['name']
            self.client.del_object(name)
        r = self.client.container_delete()
        self.container = ''

    def tearDown(self):
        """Destroy test cases"""
        for f in self.files:
            f.close()
        self.forceDeleteContainer(self.c1)
        self.forceDeleteContainer(self.c2)
        try:
            self.forceDeleteContainer(self.c3)
        except ClientError:
            pass
        self.client.container = ''

    def test_000(self):
        """Prepare a full Pithos+ test"""
        print('')
        super(self.__class__, self).test_000()

    def test_account_head(self):
        """Test account_HEAD"""
        self._test_0010_account_head()

    def _test_0010_account_head(self):
        r = self.client.account_head()
        self.assertEqual(r.status_code, 204)

        r = self.client.account_head(until='1000000000')
        self.assertEqual(r.status_code, 204)

        r = self.client.get_account_info(until='1000000000')
        datestring = unicode(r['x-account-until-timestamp'])
        self.assertEqual(u'Sun, 09 Sep 2001 01:46:40 GMT', datestring)

#.........这里部分代码省略.........
开发者ID:Erethon,项目名称:kamaki,代码行数:103,代码来源:pithos.py


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