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

Python pyrax.set_setting函数代码示例

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

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



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

示例1: get_queryset

 def get_queryset(self):
     pyrax.set_setting("identity_type", "rackspace")
     profile = UserProfile.get_profile(self.request.user)
     username = profile.rackspace_username
     api_key = profile.rackspace_api_key
     pyrax.set_credentials(username, api_key)
     return pyrax.cloudservers.list()
开发者ID:codedbyjay,项目名称:django-branches,代码行数:7,代码来源:views.py


示例2: authenticate_credentials

    def authenticate_credentials(self):
        """
        This method try to authenticate with available credentials

        :returns: True or False (Boolean)
        """
        logger = logging.getLogger(__name__)
        logger.debug('authenticating with credentials '
                     '(identity_type:%s, username:%s, api-key:%s, region=%s)',
                     self._identity_type, self._username, self._apikey, self._region)
        try:
            pyrax.set_setting("identity_type", self._identity_type)
            pyrax.set_credentials(self._username, self._apikey,
                                  region=self._region)
            logger.info("authenticated with credentials, username: %s, "
                        "api-key: %s, region: %s, identity_type: %s",
                        self._username, self._apikey, self._region, self._identity_type)
            logger.debug("user authenticated: %s", pyrax.identity.authenticated)
            if pyrax.identity.authenticated:
                self._token = pyrax.identity.auth_token
                self._tenant_id = pyrax.identity.tenant_id
                self.save_token()
            return pyrax.identity.authenticated
        except AuthenticationFailed:
            logger.warn("cannot authenticate with credentials")
            return False
开发者ID:Teddy-Schmitz,项目名称:rax-autoscaler,代码行数:26,代码来源:auth.py


示例3: __init__

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

        try:
            import pyrax
        except ImportError as e:
            raise BackendException("""\
Hubic backend requires the pyrax library available from Rackspace.
Exception: %s""" % str(e))

        # Inform Pyrax that we're talking to Hubic
        pyrax.set_setting("identity_type", "duplicity.backends.pyrax_identity.hubic.HubicIdentity")

        CREDENTIALS_FILE = os.path.expanduser("~/.hubic_credentials")
        if os.path.exists(CREDENTIALS_FILE):
            try:
                pyrax.set_credential_file(CREDENTIALS_FILE)
            except Exception as e:
                log.FatalError("Connection failed, please check your credentials: %s %s"
                               % (e.__class__.__name__, util.uexc(e)),
                               log.ErrorCode.connection_failed)

        else:
            raise BackendException("No ~/.hubic_credentials file found.")

        container = parsed_url.path.lstrip('/')

        self.client_exc = pyrax.exceptions.ClientException
        self.nso_exc = pyrax.exceptions.NoSuchObject
        self.container = pyrax.cloudfiles.create_container(container)
开发者ID:henrysher,项目名称:duplicity,代码行数:30,代码来源:hubicbackend.py


示例4: master_up

def master_up(key_name, credential_file="~/.rackspace_cloud_credentials"):
    '''
    Create a salt-master on Rackspace

    Alternatively create the master using nova
    '''

    # Authenticate with Rackspace, use credential file
    pyrax.set_setting("identity_type", "rackspace")
    pyrax.set_credential_file(os.path.expanduser(credential_file))

    # Shorthand
    cs = pyrax.cloudservers

    # Building Ubuntu 12.04 boxes with 512 MB RAM
    iter_flavors = ifilter(lambda flavor: flavor.ram == 512, cs.flavors.list())
    flavor_512 = iter_flavors.next()
    iter_os = ifilter(lambda img: "Ubuntu 12.04" in img.name, cs.images.list())
    ubu_image = iter_os.next()

    master = cs.servers.create("master.ipython.org", ubu_image.id, flavor_512,
                               key_name=key_name)

    master = pyrax.utils.wait_for_build(master, verbose=True)

    env.hosts = [master.accessIPv4]

    print("Master IP: {}".format(master.accessIPv4))
    return master.accessIPv4
开发者ID:minrk,项目名称:bootstrap-salt-nbviewer,代码行数:29,代码来源:fabfile.py


示例5: test_set_region_setting

 def test_set_region_setting(self):
     ident = pyrax.identity
     ident.region = "DFW"
     pyrax.set_setting("region", "ORD")
     self.assertEqual(ident.region, "DFW")
     pyrax.set_setting("region", "LON")
     self.assertEqual(ident.region, "LON")
开发者ID:Gu1,项目名称:pyrax,代码行数:7,代码来源:test_module.py


示例6: content_store_url

def content_store_url(quiet=False):
    """
    Access the public content store URL.

    Respect the environment variable CONTENT_STORE_URL if it is populated.
    Otherwise, find the content store load balancer and derive its public IP
    via the Rackspace API.

    Prints the derived URL to stdout as a side-effect unless "quiet" is set to
    True.
    """

    content_store_url = os.environ.get("CONTENT_STORE_URL")
    domain = get("domain")
    if content_store_url:
        if content_store_url.endswith("/"):
            content_store_url = content_store_url[:-1]

        if not quiet:
            print("Using content store URL: {}".format(content_store_url))

        return content_store_url
    elif domain:
        content_store_url = "https://{}:9000".format(domain)

        if not quiet:
            print("Using content store URL: {}".format(content_store_url))

        return content_store_url
    else:
        rackspace_username = get("rackspace_username")
        rackspace_apikey = get("rackspace_api_key")
        rackspace_region = get("rackspace_region")

        instance_name = get("instance")

        pyrax.set_setting("identity_type", "rackspace")
        pyrax.set_setting("region", rackspace_region)
        pyrax.set_credentials(rackspace_username, rackspace_apikey)
        clb = pyrax.cloud_loadbalancers

        the_lb = None
        content_lb_name = "deconst-{}-content".format(instance_name)
        for lb in clb.list():
            if lb.name == content_lb_name:
                the_lb = lb

        if not the_lb:
            raise Exception("Content service load balancer not found")

        addr = the_lb.virtual_ips[0].address
        port = the_lb.port

        content_store_url = "https://{}:{}".format(addr, port)

        if not quiet:
            print("Derived content store URL: {}".format(content_store_url))
            print("If this is incorrect, set CONTENT_STORE_URL to the correct value.")

        return content_store_url
开发者ID:everett-toews,项目名称:deploy,代码行数:60,代码来源:credentials.py


示例7: __init__

    def __init__(self, parsed_url):
        try:
            import pyrax
        except ImportError:
            raise BackendException("This backend requires the pyrax "
                                   "library available from Rackspace.")

        # Inform Pyrax that we're talking to Rackspace
        # per Jesus Monzon (gsusmonzon)
        pyrax.set_setting("identity_type", "rackspace")

        conn_kwargs = {}

        if not os.environ.has_key('CLOUDFILES_USERNAME'):
            raise BackendException('CLOUDFILES_USERNAME environment variable'
                                   'not set.')

        if not os.environ.has_key('CLOUDFILES_APIKEY'):
            raise BackendException('CLOUDFILES_APIKEY environment variable not set.')

        conn_kwargs['username'] = os.environ['CLOUDFILES_USERNAME']
        conn_kwargs['api_key'] = os.environ['CLOUDFILES_APIKEY']

        if os.environ.has_key('CLOUDFILES_REGION'):
            conn_kwargs['region'] = os.environ['CLOUDFILES_REGION']

        container = parsed_url.path.lstrip('/')

        try:
            pyrax.set_credentials(**conn_kwargs)
        except Exception, e:
            log.FatalError("Connection failed, please check your credentials: %s %s"
                           % (e.__class__.__name__, str(e)),
                           log.ErrorCode.connection_failed)
开发者ID:alanfranz,项目名称:duplicity,代码行数:34,代码来源:_cf_pyrax.py


示例8: setup

def setup():
    rax_username = get_config(p, 'rax', 'username', 'RAX_USERNAME', None)
    rax_api_key = get_config(p, 'rax', 'api_key', 'RAX_API_KEY', None)

    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_credentials(rax_username, rax_api_key)

    region = pyrax.get_setting('region')

    regions = []
    if region:
        regions.append(region)
    else:
        region_list = get_config(p, 'rax', 'regions', 'RAX_REGION', 'all',
                                 islist=True)
        for region in region_list:
            region = region.strip().upper()
            if region == 'ALL':
                regions = pyrax.regions
                break
            elif region not in pyrax.regions:
                sys.stderr.write('Unsupported region %s' % region)
                sys.exit(1)
            elif region not in regions:
                regions.append(region)

    return regions
开发者ID:shaweiguo,项目名称:deploy,代码行数:27,代码来源:rax.py


示例9: main

def main():
    # option parsing
    usage = "%prog --local /var/backup --remote backup"
    parser = OptionParser(usage=usage)
    parser.add_option("-i", "--identity", default="rackspace",
        help="Pyrax identity class")
    parser.add_option("-l", "--local", help="local path to backup")
    parser.add_option("-r", "--remote", help="remote container to backup to")
    parser.add_option("-v", "--verbose", action="count",
        help="Increase verbosity", default=0)

    (options, args) = parser.parse_args()
    for option in (options.local, options.remote):
        if option is None:
            parser.print_help()
            sys.exit(1)

    # Get login details from .netrc.
    login, account, password = netrc().authenticators(
        'pyrax.%s' % options.identity)

    # Configure logging
    logging.basicConfig(level=max(4-options.verbose,1)*10)

    logging.info("Logging on to %s", options.identity)
    pyrax.set_setting("identity_type", options.identity)
    pyrax.set_credentials(login, password)

    logging.info("Synchronising")
    pyrax.cloudfiles.sync_folder_to_container(
        options.local, options.remote, delete=True, ignore_timestamps=True)
开发者ID:izak,项目名称:backuptools,代码行数:31,代码来源:rscloudsync.py


示例10: main

def main():

	pyrax.set_setting("identity_type", "rackspace")
	creds_file = os.path.expanduser('~/.rackspace_cloud_credentials')
	pyrax.set_credential_file(creds_file)
	available_regions = pyrax.regions

	print "Regions Available:", " ".join(list(available_regions))
	region = ""
	while region not in pyrax.regions:
		region = raw_input("Select region: ")
	cs = pyrax.connect_to_cloudservers(region)
	servers = cs.servers.list()
	srv_dict = {}

	print "Select a server from which an image will be created."
	for pos, srv in enumerate(servers):
	    print "%s: %s" % (pos, srv.name)
	    srv_dict[str(pos)] = srv.id
	selection = None
	while selection not in srv_dict:
	    if selection is not None:
	        print " -- Invalid choice"
	    selection = raw_input("Enter the number for your choice: ")

	server_id = srv_dict[selection]
	print
	nm = raw_input("Enter a name for the image: ")

	img_id = cs.servers.create_image(server_id, nm)

	print "Image '%s' is being created. Its ID is: %s" % (nm, img_id)
开发者ID:r3d91ll,项目名称:RAX-CloudAPI,代码行数:32,代码来源:test.py


示例11: main

def main(username, project, list):
    pyrax.set_setting('identity_type', 'rackspace')
    with open(os.path.expanduser('~/.bugminion'), 'r') as f:
        conf = json.loads(f.read())
        pyrax.set_credentials(conf['access_key'],
                              conf['secret_key'],
                              region=conf['region'].upper())

    conn = pyrax.connect_to_cloudfiles(region=conf['region'].upper())
    container = conn.create_container(conf['container'])

    # Prioritize a list of bugs from an input file
    now = datetime.datetime.now()
    datestamp = '%04d%02d%02d' %(now.year, now.month, now.day)
    with open(list) as f:
        for bug in f.readlines():
            bug = bug.rstrip()

            triage = {'reviewer': username,
                      'osic': 'y'}
            common.clobber_object(container,
                                  '%s-bug/%s-%s' %(project, bug, datestamp),
                                  json.dumps(triage, indent=4, sort_keys=True))

    print 'Done!'
开发者ID:neillc,项目名称:bugminion,代码行数:25,代码来源:prioritize_list.py


示例12: __init__

    def __init__(self, name):
        self.region, name = name.split('://')
        self.basename = os.path.basename(name)

        pyrax.set_setting('identity_type', 'rackspace')
        with open(os.path.expanduser('~/.cloudfiles'), 'r') as f:
            self.conf = json.loads(f.read())
            pyrax.set_credentials(self.conf['access_key'],
                                  self.conf['secret_key'],
                                  region=self.region)

        conn = pyrax.connect_to_cloudfiles(region=self.region.upper())

        if self.region == 'dfw':
            self.container_name = remote_filename(name)
        else:
            self.container_name = remote_filename('%s/%s' %(self.region, name))
        container = conn.create_container(self.container_name)

        for i in range(3):
            try:
                container.log_retention(True)
                break
            except:
                pass

        for info in conn.list_containers_info():
            if info['name'] == self.container_name:
                remote_total = info['bytes']
                print ('%s Remote store %s contains %s in %d objects'
                       %(datetime.datetime.now(), self.region,
                         utility.DisplayFriendlySize(remote_total),
                         info['count']))
开发者ID:mikalstill,项目名称:cloudfiles-tools,代码行数:33,代码来源:remote_pyrax.py


示例13: main

def main():
    domain_name = sys.argv[1]

    pyrax.set_setting('identity_type', 'rackspace')
    creds_file = os.path.expanduser('~/.rackspace_cloud_credentials')
    pyrax.set_credential_file(creds_file)

    dns = pyrax.cloud_dns

    # Create the domain name.
    try:
        domain = dns.find(name=domain_name)
    except exc.NotFound:
        domain = dns.create(name=domain_name, emailAddress='[email protected]', ttl=DEFAULT_TTL)

    records = [{
        'type': 'A',
        'name': domain_name,
        'data': MVPCREATOR_IP,
        'ttl': DEFAULT_TTL,
    }, {
        'type': 'CNAME',
        'name': '*.' + domain_name,
        'data': domain_name,
        'ttl': DEFAULT_TTL,
    }]

    domain.add_records(records)
开发者ID:dsnopek,项目名称:rackspace-dns,代码行数:28,代码来源:add-domain.py


示例14: mount

def mount(volume_name, server_name, etcd):
    resp = requests.get(
        build_url(etcd, 'rackspace', 'credentials')
    ).json()

    credentials = json.loads(resp['node']['value'])

    username = credentials['username']
    api_key = credentials['apiKey']
    region = credentials['region']

    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_credentials(username, api_key, region=region)

    cs = pyrax.cloudservers
    cbs = pyrax.cloud_blockstorage

    volume = cbs.find(display_name=volume_name)
    server = cs.servers.find(name=server_name)

    if volume.attachments and volume.attachments[0]['server_id'] != server.id:
        volume.detach()
        pyrax.utils.wait_until(volume, 'status', 'available', interval=3, attempts=0)

    if not volume.attachments:
        volume.attach_to_instance(server, mountpoint='')
        pyrax.utils.wait_until(volume, 'status', 'in-use', interval=3, attempts=0)

    resp = requests.put(
        build_url(etcd, 'rackspace', 'cbs', volume_name),
        data={"value": volume.attachments[0]['device']}
    )
开发者ID:CenterForOpenScience,项目名称:docker-library,代码行数:32,代码来源:tasks.py


示例15: provision

def provision():
    # Set the credentials for pyrax
    pyrax.set_setting("identity_type", "rackspace")
    pyrax.set_credential_file(".pyrax.cfg")

    # Provision the server with Rackspace
    server = pyrax.cloudservers.servers.create(
        "warehouse-repository",
        IMAGE_ID,
        FLAVOR_ID,
    )

    # Store the password
    fabric.state.env.password = server.adminPass

    # Wait until the server is built
    server = pyrax.utils.wait_for_build(server)

    fabric.state.env.host_string = "[email protected]{}".format(
        filter(lambda x: "." in x, server.networks["public"])[0],
    )

    # Bootstrap our environment
    _bootstrap_environment()

    # Write out our config
    with open(".rackspace.json", "w") as rs:
        json.dump(
            {
                "host_string": fabric.state.env.host_string,
                "password": fabric.state.env.password,
            },
            rs,
        )
开发者ID:Ivoz,项目名称:warehouse,代码行数:34,代码来源:deploy.py


示例16: main

def main(username, project, list):
    pyrax.set_setting('identity_type', 'rackspace')
    with open(os.path.expanduser('~/.bugminion'), 'r') as f:
        conf = json.loads(f.read())
        pyrax.set_credentials(conf['access_key'],
                              conf['secret_key'],
                              region=conf['region'].upper())

    conn = pyrax.connect_to_cloudfiles(region=conf['region'].upper())
    container = conn.create_container(conf['container'])

    now = datetime.datetime.now()
    datestamp = '%04d%02d%02d' %(now.year, now.month, now.day)
    with open(list) as f:
        with open('%s.csv' % list, 'w') as csvfile:
            csvwriter = csv.writer(csvfile, dialect='excel')
            for bug in f.readlines():
                bug = bug.rstrip()

                try:
                    data = json.loads(container.get_object(
                        '%s-bug/%s' %(project, bug)).get())
                except pyrax.exceptions.NoSuchObject:
                    data = {}

                csvwriter.writerow([
                    'https://bugs.launchpad.net/nova/+bug/%s' % bug,
                    data.get('title', 'unknown'),
                    data.get('status', 'unknown'),
                    username])

    print 'Done!'
开发者ID:neillc,项目名称:bugminion,代码行数:32,代码来源:spreadsheetize_list.py


示例17: cloud_connect

def cloud_connect():
    creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
    try:
        pyrax.set_setting("identity_type", "rackspace")
        pyrax.set_credential_file(creds_file)
    except exc.AuthenticationFailed:
        print "Problem with credential file ~/.rackspace_cloud_credentials"
开发者ID:chris-mendoza,项目名称:cloud-examples,代码行数:7,代码来源:cloud_lb.py


示例18: __init__

    def __init__(self, task_kwargs=None, json_config_file=None):
        json_config_file = json_config_file or './deploy_settings.json'
        self.cloudservers = None
        self.settings = AttributeDict({})
        self.fabric_env_servers = []
        self.created_servers = []

        task_kwargs = task_kwargs or {}

        settings = self.read_settings_file(json_config_file)

        for key in self.SETTINGS_KEYS:
            try:
                self.settings[key] = task_kwargs[key]
            except KeyError:
                try:
                    self.settings[key] = environ[key]
                except KeyError:
                    try:
                        self.settings[key] = settings[key]
                    except KeyError:
                        pass

        self.settings.server_count = int(self.settings.server_count)
        self.settings.setdefault('ssh_user', 'root')
        self.settings.setdefault('git_branch', 'master')
        self.ensure_settings('rackspace_username', 'rackspace_apikey')

        pyrax.set_setting('identity_type', 'rackspace')
        pyrax.set_credentials(
            self.settings.rackspace_username,
            self.settings.rackspace_apikey)
        self.cloudservers = pyrax.connect_to_cloudservers()
        self.loadbalancers = pyrax.connect_to_cloud_loadbalancers()
开发者ID:mobilerider,项目名称:medusa-for-rack,代码行数:34,代码来源:tasks.py


示例19: update_records

 def update_records(self, ip_addresses):
     record_types = {
         'ipv4': 'A',
         'ipv6': 'AAAA'
     }
     username = self.config_get('username')
     if username is None:
         raise exc.NoUsername('A username is not configured in %s' %
                              self.config_file)
     apikey = self.config_get('apikey')
     if apikey is None:
         raise exc.NoApiKey('An API key is not configured in %s' %
                            self.config_file)
     pyrax.set_setting('identity_type', 'rackspace')
     pyrax.set_credentials(username, apikey)
     self.dns = pyrax.cloud_dns
     dns_info = self.find_dns()
     for ip_type, ip in ip_addresses.iteritems():
         if ip is None:
             continue
         if dns_info[ip_type] is None:
             self.logger.info('Creating %s record for %s' %
                              (record_types[ip_type], dns_info['host']))
             records = dns_info['domain'].add_records([
                 {
                     'type': record_types[ip_type],
                     'name': dns_info['host'],
                     'data': ip,
                     'ttl': 300
                 }
             ])
         else:
             self.logger.info('Updating %s record for %s' %
                              (record_types[ip_type], dns_info['host']))
             dns_info[ip_type].update(data=ip)
开发者ID:dsqmoore,项目名称:raxdyndns,代码行数:35,代码来源:__init__.py


示例20: main

def main():
    '''Script execution'''
    parser = argparse.ArgumentParser(description='get percent of api limit '
                                                 'of ram used')
    parser.add_argument('-u', '--username', help='Rackspace Username',
                        required=True)
    parser.add_argument('-a', '--apikey', help='Rackspace API Key',
                        required=True)
    parser.add_argument('-m', '--maxthreshold',
                        help='API Percent Used Threshold, integer between '
                             '1-99',
                        required=True)
    parser.add_argument('-r', '--region', help='Rackspace Regional Datacenter',
                                required=True)
    parser.add_argument('--human',
                        help='Format output for humans, not Cloud Monitoring',
                        action='store_true')
    args = parser.parse_args()

    if int(args.maxthreshold) < 1 or int(args.maxthreshold) > 99:
        print "You must enter a valid integer from 1-99 for maxthreshold"
        sys.exit(2)
    pyrax.set_setting("identity_type", "rackspace")
    pyrax.set_credentials(args.username, args.apikey)

    (ram_used, ram_allowed) = getlimits(args.region)
    display_usage(ram_used, ram_allowed, args.maxthreshold, args.human)
开发者ID:1T,项目名称:rackspace-monitoring-agent-plugins-contrib,代码行数:27,代码来源:api_limit_ram_usage.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python clouddatabases.CloudDatabaseUser类代码示例发布时间:2022-05-27
下一篇:
Python pyrax.set_default_region函数代码示例发布时间: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