本文整理汇总了Python中pyrax.set_credentials函数的典型用法代码示例。如果您正苦于以下问题:Python set_credentials函数的具体用法?Python set_credentials怎么用?Python set_credentials使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了set_credentials函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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!'
示例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']))
示例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']}
)
示例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)
示例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)
示例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
示例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
示例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)
示例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)
示例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)
示例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
示例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)
示例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
示例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