本文整理汇总了Python中pyrax.set_credentials函数的典型用法代码示例。如果您正苦于以下问题:Python set_credentials函数的具体用法?Python set_credentials怎么用?Python set_credentials使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了set_credentials函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: 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
示例2: 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
示例3: __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
示例4: 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
示例5: 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
示例6: setup
def setup():
username = os.environ.get('OS_USERNAME')
api_key = os.environ.get('OS_PASSWORD')
credentials = os.environ.get('RAX_CREDENTIALS') or os.environ.get('RAX_CREDS_FILE')
region = os.environ.get('OS_REGION_NAME')
if credentials is None:
credentails = os.path.expanduser('~/.rackspace_cloud_credentials')
try:
pyrax.set_setting('identity_type', 'rackspace')
if api_key and username:
pyrax.set_credentials(username, api_key=api_key)
elif credentials:
credentials = os.path.expanduser(credentials)
pyrax.set_credential_file(credentials)
else:
sys.stderr.write('No value in environment variable %s and/or no '
'credentials file at %s\n'
% (e.message, default_creds_file))
sys.exit(1)
except Exception, e:
sys.stderr.write("%s: %s\n" % (e, e.message))
sys.exit(1)
开发者ID:chalupaul,项目名称:ansible-zwift,代码行数:25,代码来源:rax.py
示例7: create_table
def create_table(username, apikey):
pyrax.set_credentials(username, apikey)
raw_server_list = pyrax.cloudservers.list()
raw_network_list = pyrax.cloud_networks.list()
raw_flavor_list = pyrax.cloudservers.flavors.list()
flavor_dict = {}
for flavor in raw_flavor_list:
flavor_dict[flavor.id] = flavor.name
headers = ['UUID',
'name',
'RackConnect status',
'flavor',
'accessIPv4']
network_list = []
for each in raw_network_list:
network_list.append(each.label)
headers += network_list
output = prettytable.PrettyTable(headers)
for server in raw_server_list:
row = server_data(server, network_list, flavor_dict)
output.add_row(row)
output.align = 'l'
output.sortby = 'name'
return output
开发者ID:carlwgeorge,项目名称:scripts,代码行数:25,代码来源:cloudinventory.py
示例8: upload
def upload(self, local_dir, cf_prefix, container_name=None):
pyrax.set_setting('identity_type', 'rackspace')
try:
pyrax.set_credentials(Configuration().SWIFT_USERNAME, Configuration().SWIFT_API_KEY)
except pyrax.exceptions.AuthenticationFailed, e:
self.logger.exception(e)
raise
开发者ID:BobBall,项目名称:openstack-citrix-ci,代码行数:7,代码来源:swift_upload.py
示例9: 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
示例10: __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
示例11: url_for
def url_for(endpoint, **values):
"""
Generates a URL to the given endpoint.
If the endpoint is for a static resource then a Rackspace Cloud File URL is
generated, otherwise the call is passed on to `flask.url_for`.
Because this function is set as a jinja environment variable when
`FlaskRSF.init_app` is invoked, this function replaces `flask.url_for` in
templates automatically. It is unlikely that this function will
need to be directly called from within your application code, unless you
need to refer to static assets outside of your templates.
"""
app = current_app
if "RSF_CONTAINER_NAME" not in app.config:
raise ValueError("RSF_CONTAINER_NAME not found in app configuration.")
if app.debug and not app.config["USE_RSF_DEBUG"]:
return flask_url_for(endpoint, **values)
if endpoint == "static" or endpoint.endswith(".static"):
pyrax.set_credentials(["RSF_USERNAME"], ["RSF_API_KEY"])
cf = pyrax.cloudfiles
cont = cf.create_container(app.config["RSF_CONTAINER_NAME"])
scheme = "http"
bucket_path = cont.cdn_uri
if app.config["RSF_USE_HTTPS"]:
scheme = "https"
bucket_path = cont.cdn_ssl_uri
bucket_path = re.sub(r"(http[s]*://)", r"", bucket_path)
urls = app.url_map.bind(bucket_path, url_scheme=scheme)
return urls.build(endpoint, values=values, force_external=True)
return flask_url_for(endpoint, **values)
开发者ID:robv,项目名称:flask-rackspace-cloud-files,代码行数:33,代码来源:flask_rsf.py
示例12: 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
示例13: connect_container
def connect_container(self):
"""
Connects to a container using the swiftclient api.
The container will be created and/or made public using the
pyrax api if not already so.
"""
self.conn = swiftclient.Connection(authurl=CUMULUS["AUTH_URL"],
user=CUMULUS["USERNAME"],
key=CUMULUS["API_KEY"],
snet=CUMULUS["SERVICENET"],
auth_version=CUMULUS["AUTH_VERSION"],
tenant_name=CUMULUS["AUTH_TENANT_NAME"])
try:
self.conn.head_container(self.container_name)
except swiftclient.client.ClientException as exception:
if exception.msg == "Container HEAD failed":
call_command("container_create", self.container_name)
else:
raise
if CUMULUS["USE_PYRAX"]:
public = not CUMULUS["SERVICENET"]
pyrax.set_credentials(CUMULUS["USERNAME"], CUMULUS["API_KEY"])
connection = pyrax.connect_to_cloudfiles(region=CUMULUS["REGION"],
public=public)
container = connection.get_container(self.container_name)
if not container.cdn_enabled:
container.make_public(ttl=CUMULUS["TTL"])
else:
headers = {"X-Container-Read": ".r:*"}
self.conn.post_container(self.container_name, headers=headers)
self.container = self.conn.get_container(self.container_name)
开发者ID:ZG-Tennis,项目名称:django-cumulus,代码行数:34,代码来源:syncstatic.py
示例14: 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
示例15: login
def login(self):
"""
Logs into cloud files. Note that this is on the main thread.
init_thread is responsible for initializing individual threads.
:return: True on success, false on failure
"""
try:
pyrax.set_credentials(username=self.username,
api_key=self.api_key)
self.rax = pyrax.connect_to_cloudfiles(self.region, True)
if self.rax is None:
ThreadedDeleter.output('Unknown error occured while connecting'
' to CloudFiles.')
return False
except pyrax.exceptions.AuthenticationFailed as e:
ThreadedDeleter.output('Authentication failed: {msg}'.format(
msg=str(e)))
return False
except pyrax.exceptions.PyraxException as e:
ThreadedDeleter.output('Unknown error occurred: {msg}'.format(
msg=str(e)))
return False
return True
开发者ID:curquhart,项目名称:threadedobjectdeleter,代码行数:25,代码来源:cloudfiles.py
示例16: 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
示例17: 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
示例18: impl
def impl(context, operating_system, ram_size):
server_id = context.output.strip()
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credentials(os.environ['OS_USERNAME'], os.environ['OS_PASSWORD'])
cs = pyrax.cloudservers
import code
code.interact(local=locals())
开发者ID:maxlinc,项目名称:behave-relish,代码行数:7,代码来源:servers.py
示例19: __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
示例20: 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
注:本文中的pyrax.set_credentials函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论