desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Asserts that all expected calls were made.'
| def assert_no_pending_responses(self):
| remaining = len(self._queue)
if (remaining != 0):
raise AssertionError(('%d responses remaining in queue.' % remaining))
|
'Constructs a :class:`AWSPreparedRequest <AWSPreparedRequest>`.'
| def prepare(self):
| p = AWSPreparedRequest(self)
p.prepare_method(self.method)
p.prepare_url(self.url, self.params)
p.prepare_headers(self.headers)
p.prepare_cookies(self.cookies)
p.prepare_body(self.data, self.files)
p.prepare_auth(self.auth)
return p
|
'Prepares the given HTTP body data.'
| def prepare_body(self, data, files, json=None):
| super(AWSPreparedRequest, self).prepare_body(data, files, json)
if ('Content-Length' not in self.headers):
if (hasattr(data, 'seek') and hasattr(data, 'tell')):
orig_pos = data.tell()
data.seek(0, 2)
end_file_pos = data.tell()
self.headers['Content-Length'... |
'Encodes a dictionary to an opaque string.
:type token: dict
:param token: A dictionary containing pagination information,
particularly the service pagination token(s) but also other boto
metadata.
:rtype: str
:returns: An opaque string'
| def encode(self, token):
| try:
json_string = json.dumps(token)
except (TypeError, UnicodeDecodeError):
(encoded_token, encoded_keys) = self._encode(token, [])
encoded_token['boto_encoded_keys'] = encoded_keys
json_string = json.dumps(encoded_token)
return base64.b64encode(json_string.encode('utf-8')).... |
'Encode bytes in given data, keeping track of the path traversed.'
| def _encode(self, data, path):
| if isinstance(data, dict):
return self._encode_dict(data, path)
elif isinstance(data, list):
return self._encode_list(data, path)
elif isinstance(data, six.binary_type):
return self._encode_bytes(data, path)
else:
return (data, [])
|
'Encode any bytes in a list, noting the index of what is encoded.'
| def _encode_list(self, data, path):
| new_data = []
encoded = []
for (i, value) in enumerate(data):
new_path = (path + [i])
(new_value, new_encoded) = self._encode(value, new_path)
new_data.append(new_value)
encoded.extend(new_encoded)
return (new_data, encoded)
|
'Encode any bytes in a dict, noting the index of what is encoded.'
| def _encode_dict(self, data, path):
| new_data = {}
encoded = []
for (key, value) in data.items():
new_path = (path + [key])
(new_value, new_encoded) = self._encode(value, new_path)
new_data[key] = new_value
encoded.extend(new_encoded)
return (new_data, encoded)
|
'Base64 encode a byte string.'
| def _encode_bytes(self, data, path):
| return (base64.b64encode(data).decode('utf-8'), [path])
|
'Decodes an opaque string to a dictionary.
:type token: str
:param token: A token string given by the botocore pagination
interface.
:rtype: dict
:returns: A dictionary containing pagination information,
particularly the service pagination token(s) but also other boto
metadata.'
| def decode(self, token):
| json_string = base64.b64decode(token.encode('utf-8')).decode('utf-8')
decoded_token = json.loads(json_string)
encoded_keys = decoded_token.pop('boto_encoded_keys', None)
if (encoded_keys is None):
return decoded_token
else:
return self._decode(decoded_token, encoded_keys)
|
'Find each encoded value and decode it.'
| def _decode(self, token, encoded_keys):
| for key in encoded_keys:
encoded = self._path_get(token, key)
decoded = base64.b64decode(encoded.encode('utf-8'))
self._path_set(token, key, decoded)
return token
|
'Return the nested data at the given path.
For instance:
data = {\'foo\': [\'bar\', \'baz\']}
path = [\'foo\', 0]
==> \'bar\''
| def _path_get(self, data, path):
| d = data
for step in path:
d = d[step]
return d
|
'Set the value of a key in the given data.
Example:
data = {\'foo\': [\'bar\', \'baz\']}
path = [\'foo\', 1]
value = \'bin\'
==> data = {\'foo\': [\'bar\', \'bin\']}'
| def _path_set(self, data, path, value):
| container = self._path_get(data, path[:(-1)])
container[path[(-1)]] = value
|
'Token to specify to resume pagination.'
| @property
def resume_token(self):
| return self._resume_token
|
'Applies a JMESPath expression to a paginator
Each page of results is searched using the provided JMESPath
expression. If the result is not a list, it is yielded
directly. If the result is a list, each element in the result
is yielded individually (essentially implementing a flatmap in
which the JMESPath search is the ... | def search(self, expression):
| compiled = jmespath.compile(expression)
for page in self:
results = compiled.search(page)
if isinstance(results, list):
for element in results:
(yield element)
else:
(yield results)
|
'This handles parsing of old style starting tokens, and attempts to
coerce them into the new style.'
| def _parse_starting_token_deprecated(self):
| log.debug(('Attempting to fall back to old starting token parser. For token: %s' % self._starting_token))
if (self._starting_token is None):
return None
parts = self._starting_token.split('___')
next_token = []
index = 0
if (len(parts) == (len(self._input... |
'This attempts to convert a deprecated starting token into the new
style.'
| def _convert_deprecated_starting_token(self, deprecated_token):
| len_deprecated_token = len(deprecated_token)
len_input_token = len(self._input_token)
if (len_deprecated_token > len_input_token):
raise ValueError(('Bad starting token: %s' % self._starting_token))
elif (len_deprecated_token < len_input_token):
log.debug('Old format start... |
'Create paginator object for an operation.
This returns an iterable object. Iterating over
this object will yield a single page of a response
at a time.'
| def paginate(self, **kwargs):
| page_params = self._extract_paging_params(kwargs)
return self.PAGE_ITERATOR_CLS(self._method, self._input_token, self._output_token, self._more_results, self._result_keys, self._non_aggregate_keys, self._limit_key, page_params['MaxItems'], page_params['StartingToken'], page_params['PageSize'], kwargs)
|
'Select the headers from the request that need to be included
in the StringToSign.'
| def headers_to_sign(self, request):
| header_map = HTTPHeaders()
split = urlsplit(request.url)
for (name, value) in request.headers.items():
lname = name.lower()
if (lname not in SIGNED_HEADERS_BLACKLIST):
header_map[lname] = value
if ('host' not in header_map):
header_map['host'] = split.netloc
retur... |
'Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines.'
| def canonical_headers(self, headers_to_sign):
| headers = []
sorted_header_names = sorted(set(headers_to_sign))
for key in sorted_header_names:
value = ','.join((self._header_value(v) for v in sorted(headers_to_sign.get_all(key))))
headers.append(('%s:%s' % (key, ensure_unicode(value))))
return '\n'.join(headers)
|
'Return the canonical StringToSign as well as a dict
containing the original version of all headers that
were included in the StringToSign.'
| def string_to_sign(self, request, canonical_request):
| sts = ['AWS4-HMAC-SHA256']
sts.append(request.context['timestamp'])
sts.append(self.credential_scope(request))
sts.append(sha256(canonical_request.encode('utf-8')).hexdigest())
return '\n'.join(sts)
|
'TODO: Do we need this?'
| def unquote_v(self, nv):
| if (len(nv) == 1):
return nv
else:
return (nv[0], unquote(nv[1]))
|
'Returns the \'s3\' (sigv2) signer if presigning an s3 request. This is
intended to be used to set the default signature version for the signer
to sigv2.
:type signature_version: str
:param signature_version: The current client signature version.
:type signing_name: str
:param signing_name: The signing name of the serv... | def _default_s3_presign_to_sigv2(self, signature_version, **kwargs):
| for suffix in ['-query', '-presign-post']:
if signature_version.endswith(suffix):
return ('s3' + suffix)
|
'Create a paginator for an operation.
:type operation_name: string
:param operation_name: The operation name. This is the same name
as the method name on the client. For example, if the
method name is ``create_foo``, and you\'d normally invoke the
operation as ``client.create_foo(**kwargs)``, if the
``create_foo`` op... | def get_paginator(self, operation_name):
| if (not self.can_paginate(operation_name)):
raise OperationNotPageableError(operation_name=operation_name)
else:
actual_operation_name = self._PY_TO_OP_NAME[operation_name]
def paginate(self, **kwargs):
return Paginator.paginate(self, **kwargs)
paginator_config = self... |
'Check if an operation can be paginated.
:type operation_name: string
:param operation_name: The operation name. This is the same name
as the method name on the client. For example, if the
method name is ``create_foo``, and you\'d normally invoke the
operation as ``client.create_foo(**kwargs)``, if the
``create_foo``... | def can_paginate(self, operation_name):
| if ('page_config' not in self._cache):
try:
page_config = self._loader.load_service_model(self._service_model.service_name, 'paginators-1', self._service_model.api_version)['pagination']
self._cache['page_config'] = page_config
except DataNotFoundError:
self._cach... |
'Returns a list of all available waiters.'
| @CachedProperty
def waiter_names(self):
| config = self._get_waiter_config()
if (not config):
return []
model = waiter.WaiterModel(config)
return [xform_name(name) for name in model.waiter_names]
|
'Call all handlers subscribed to an event.
:type event_name: str
:param event_name: The name of the event to emit.
:type **kwargs: dict
:param **kwargs: Arbitrary kwargs to pass through to the
subscribed handlers. The ``event_name`` will be injected
into the kwargs so it\'s not necesary to add this to **kwargs.
:rtype... | def emit(self, event_name, **kwargs):
| return []
|
'Register an event handler for a given event.
If a ``unique_id`` is given, the handler will not be registered
if a handler with the ``unique_id`` has already been registered.
Handlers are called in the order they have been registered.
Note handlers can also be registered with ``register_first()``
and ``register_last()`... | def register(self, event_name, handler, unique_id=None, unique_id_uses_count=False):
| self._verify_and_register(event_name, handler, unique_id, register_method=self._register, unique_id_uses_count=unique_id_uses_count)
|
'Register an event handler to be called first for an event.
All event handlers registered with ``register_first()`` will
be called before handlers registered with ``register()`` and
``register_last()``.'
| def register_first(self, event_name, handler, unique_id=None, unique_id_uses_count=False):
| self._verify_and_register(event_name, handler, unique_id, register_method=self._register_first, unique_id_uses_count=unique_id_uses_count)
|
'Register an event handler to be called last for an event.
All event handlers registered with ``register_last()`` will be called
after handlers registered with ``register_first()`` and ``register()``.'
| def register_last(self, event_name, handler, unique_id=None, unique_id_uses_count=False):
| self._verify_and_register(event_name, handler, unique_id, register_method=self._register_last, unique_id_uses_count=unique_id_uses_count)
|
'Unregister an event handler for a given event.
If no ``unique_id`` was given during registration, then the
first instance of the event handler is removed (if the event
handler has been registered multiple times).'
| def unregister(self, event_name, handler=None, unique_id=None, unique_id_uses_count=False):
| pass
|
'Verifies a callable accepts kwargs
:type func: callable
:param func: A callable object.
:returns: True, if ``func`` accepts kwargs, otherwise False.'
| def _verify_accept_kwargs(self, func):
| try:
if (not accepts_kwargs(func)):
raise ValueError(('Event handler %s must accept keyword arguments (**kwargs)' % func))
except TypeError:
return False
|
'Emit an event with optional keyword arguments.
:type event_name: string
:param event_name: Name of the event
:type kwargs: dict
:param kwargs: Arguments to be passed to the handler functions.
:type stop_on_response: boolean
:param stop_on_response: Whether to stop on the first non-None
response. If False, then all han... | def _emit(self, event_name, kwargs, stop_on_response=False):
| responses = []
handlers_to_call = self._lookup_cache.get(event_name)
if (handlers_to_call is None):
handlers_to_call = self._handlers.prefix_search(event_name)
self._lookup_cache[event_name] = handlers_to_call
elif (not handlers_to_call):
return []
kwargs['event_name'] = even... |
'Emit an event by name with arguments passed as keyword args.
>>> responses = emitter.emit(
... \'my-event.service.operation\', arg1=\'one\', arg2=\'two\')
:rtype: list
:return: List of (handler, response) tuples from all processed
handlers.'
| def emit(self, event_name, **kwargs):
| return self._emit(event_name, kwargs)
|
'Emit an event by name with arguments passed as keyword args,
until the first non-``None`` response is received. This
method prevents subsequent handlers from being invoked.
>>> handler, response = emitter.emit_until_response(
\'my-event.service.operation\', arg1=\'one\', arg2=\'two\')
:rtype: tuple
:return: The first ... | def emit_until_response(self, event_name, **kwargs):
| responses = self._emit(event_name, kwargs, stop_on_response=True)
if responses:
return responses[(-1)]
else:
return (None, None)
|
'Add an item to a key.
If a value is already associated with that key, the new
value is appended to the list for the key.'
| def append_item(self, key, value, section=_MIDDLE):
| key_parts = key.split('.')
current = self._root
for part in key_parts:
if (part not in current['children']):
new_child = {'chunk': part, 'values': None, 'children': {}}
current['children'][part] = new_child
current = new_child
else:
current = c... |
'Collect all items that are prefixes of key.
Prefix in this case are delineated by \'.\' characters so
\'foo.bar.baz\' is a 3 chunk sequence of 3 "prefixes" (
"foo", "bar", and "baz").'
| def prefix_search(self, key):
| collected = deque()
key_parts = key.split('.')
current = self._root
self._get_items(current, key_parts, collected, 0)
return collected
|
'Remove an item associated with a key.
If the value is not associated with the key a ``ValueError``
will be raised. If the key does not exist in the trie, a
``ValueError`` will be raised.'
| def remove_item(self, key, value):
| key_parts = key.split('.')
current = self._root
self._remove_item(current, key_parts, value, index=0)
|
'Create a new Session object.
:type session_vars: dict
:param session_vars: A dictionary that is used to override some or all
of the environment variables associated with this session. The
key/value pairs defined in this dictionary will override the
corresponding variables defined in ``SESSION_VARIABLES``.
:type event... | def __init__(self, session_vars=None, event_hooks=None, include_builtin_handlers=True, profile=None):
| self.session_var_map = copy.copy(self.SESSION_VARIABLES)
if session_vars:
self.session_var_map.update(session_vars)
if (event_hooks is None):
self._events = HierarchicalEmitter()
else:
self._events = event_hooks
if include_builtin_handlers:
self._register_builtin_hand... |
'Retrieve the value associated with the specified logical_name
from the environment or the config file. Values found in the
environment variable take precedence of values found in the
config file. If no value can be found, a None will be returned.
:type logical_name: str
:param logical_name: The logical name of the s... | def get_config_variable(self, logical_name, methods=('instance', 'env', 'config')):
| if (logical_name not in self.session_var_map):
return
value = None
var_config = self.session_var_map[logical_name]
if self._found_in_instance_vars(methods, logical_name):
return self._session_instance_vars[logical_name]
elif self._found_in_env(methods, var_config):
value = se... |
'Set a configuration variable to a specific value.
By using this method, you can override the normal lookup
process used in ``get_config_variable`` by explicitly setting
a value. Subsequent calls to ``get_config_variable`` will
use the ``value``. This gives you per-session specific
configuration values.
>>> # Assume ... | def set_config_variable(self, logical_name, value):
| self._session_instance_vars[logical_name] = value
|
'Returns the config values from the config file scoped to the current
profile.
The configuration data is loaded **only** from the config file.
It does not resolve variables based on different locations
(e.g. first from the session instance, then from environment
variables, then from the config file). If you want this ... | def get_scoped_config(self):
| profile_name = self.get_config_variable('profile')
profile_map = self._build_profile_map()
if (profile_name is None):
return profile_map.get('default', {})
elif (profile_name not in profile_map):
raise ProfileNotFound(profile=profile_name)
else:
return profile_map[profile_nam... |
'Return the parsed config file.
The ``get_config`` method returns the config associated with the
specified profile. This property returns the contents of the
**entire** config file.
:rtype: dict'
| @property
def full_config(self):
| if (self._config is None):
try:
config_file = self.get_config_variable('config_file')
self._config = botocore.configloader.load_config(config_file)
except ConfigNotFound:
self._config = {'profiles': {}}
try:
cred_file = self.get_config_variable... |
'Retrieves the default config for creating clients
:rtype: botocore.client.Config
:returns: The default client config object when creating clients. If
the value is ``None`` then there is no default config object
attached to the session.'
| def get_default_client_config(self):
| return self._client_config
|
'Sets the default config for creating clients
:type client_config: botocore.client.Config
:param client_config: The default client config object when creating
clients. If the value is ``None`` then there is no default config
object attached to the session.'
| def set_default_client_config(self, client_config):
| self._client_config = client_config
|
'Manually create credentials for this session. If you would
prefer to use botocore without a config file, environment variables,
or IAM roles, you can pass explicit credentials into this
method to establish credentials for this session.
:type access_key: str
:param access_key: The access key part of the credentials.
:... | def set_credentials(self, access_key, secret_key, token=None):
| self._credentials = botocore.credentials.Credentials(access_key, secret_key, token)
|
'Return the :class:`botocore.credential.Credential` object
associated with this session. If the credentials have not
yet been loaded, this will attempt to load them. If they
have already been loaded, this will return the cached
credentials.'
| def get_credentials(self):
| if (self._credentials is None):
self._credentials = self._components.get_component('credential_provider').load_credentials()
return self._credentials
|
'Return a string suitable for use as a User-Agent header.
The string will be of the form:
<agent_name>/<agent_version> Python/<py_ver> <plat_name>/<plat_ver> <exec_env>
Where:
- agent_name is the value of the `user_agent_name` attribute
of the session object (`Boto` by default).
- agent_version is the value of the `use... | def user_agent(self):
| base = ('%s/%s Python/%s %s/%s' % (self.user_agent_name, self.user_agent_version, platform.python_version(), platform.system(), platform.release()))
if (os.environ.get('AWS_EXECUTION_ENV') is not None):
base += (' exec-env/%s' % os.environ.get('AWS_EXECUTION_ENV'))
if self.user_agent_extra:... |
'Retrieve the data associated with `data_path`.
:type data_path: str
:param data_path: The path to the data you wish to retrieve.'
| def get_data(self, data_path):
| return self.get_component('data_loader').load_data(data_path)
|
'Get the service model object.
:type service_name: string
:param service_name: The service name
:type api_version: string
:param api_version: The API version of the service. If none is
provided, then the latest API version will be used.
:rtype: L{botocore.model.ServiceModel}
:return: The botocore service model for the... | def get_service_model(self, service_name, api_version=None):
| service_description = self.get_service_data(service_name, api_version)
return ServiceModel(service_description, service_name=service_name)
|
'Retrieve the fully merged data associated with a service.'
| def get_service_data(self, service_name, api_version=None):
| data_path = service_name
service_data = self.get_component('data_loader').load_service_model(data_path, type_name='service-2', api_version=api_version)
self._events.emit(('service-data-loaded.%s' % service_name), service_data=service_data, service_name=service_name, session=self)
return service_data
|
'Return a list of names of available services.'
| def get_available_services(self):
| return self.get_component('data_loader').list_available_services(type_name='service-2')
|
'Convenience function to quickly configure full debug output
to go to the console.'
| def set_debug_logger(self, logger_name='botocore'):
| self.set_stream_logger(logger_name, logging.DEBUG)
|
'Convenience method to configure a stream logger.
:type logger_name: str
:param logger_name: The name of the logger to configure
:type log_level: str
:param log_level: The log level to set for the logger. This
is any param supported by the ``.setLevel()`` method of
a ``Log`` object.
:type stream: file
:param stream: A... | def set_stream_logger(self, logger_name, log_level, stream=None, format_string=None):
| log = logging.getLogger(logger_name)
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler(stream)
ch.setLevel(log_level)
if (format_string is None):
format_string = self.LOG_FORMAT
formatter = logging.Formatter(format_string)
ch.setFormatter(formatter)
log.addHandler(ch)
|
'Convenience function to quickly configure any level of logging
to a file.
:type log_level: int
:param log_level: A log level as specified in the `logging` module
:type path: string
:param path: Path to the log file. The file will be created
if it doesn\'t already exist.'
| def set_file_logger(self, log_level, path, logger_name='botocore'):
| log = logging.getLogger(logger_name)
log.setLevel(logging.DEBUG)
ch = logging.FileHandler(path)
ch.setLevel(log_level)
formatter = logging.Formatter(self.LOG_FORMAT)
ch.setFormatter(formatter)
log.addHandler(ch)
|
'Register a handler with an event.
:type event_name: str
:param event_name: The name of the event.
:type handler: callable
:param handler: The callback to invoke when the event
is emitted. This object must be callable, and must
accept ``**kwargs``. If either of these preconditions are
not met, a ``ValueError`` will b... | def register(self, event_name, handler, unique_id=None, unique_id_uses_count=False):
| self._events.register(event_name, handler, unique_id, unique_id_uses_count=unique_id_uses_count)
|
'Unregister a handler with an event.
:type event_name: str
:param event_name: The name of the event.
:type handler: callable
:param handler: The callback to unregister.
:type unique_id: str
:param unique_id: A unique identifier identifying the callback
to unregister. You can provide either the handler or the
unique_id... | def unregister(self, event_name, handler=None, unique_id=None, unique_id_uses_count=False):
| self._events.unregister(event_name, handler=handler, unique_id=unique_id, unique_id_uses_count=unique_id_uses_count)
|
'Create a botocore client.
:type service_name: string
:param service_name: The name of the service for which a client will
be created. You can use the ``Sesssion.get_available_services()``
method to get a list of all available service names.
:type region_name: string
:param region_name: The name of the region associat... | def create_client(self, service_name, region_name=None, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, config=None):
| default_client_config = self.get_default_client_config()
if ((config is not None) and (default_client_config is not None)):
config = default_client_config.merge(config)
elif (default_client_config is not None):
config = default_client_config
if (region_name is None):
if (config a... |
'Lists the available partitions found on disk
:rtype: list
:return: Returns a list of partition names (e.g., ["aws", "aws-cn"])'
| def get_available_partitions(self):
| resolver = self.get_component('endpoint_resolver')
return resolver.get_available_partitions()
|
'Lists the region and endpoint names of a particular partition.
:type service_name: string
:param service_name: Name of a service to list endpoint for (e.g., s3).
This parameter accepts a service name (e.g., "elb") or endpoint
prefix (e.g., "elasticloadbalancing").
:type partition_name: string
:param partition_name: Na... | def get_available_regions(self, service_name, partition_name='aws', allow_non_regional=False):
| resolver = self.get_component('endpoint_resolver')
results = []
try:
service_data = self.get_service_data(service_name)
endpoint_prefix = service_data['metadata'].get('endpointPrefix', service_name)
results = resolver.get_available_endpoints(endpoint_prefix, partition_name, allow_non... |
'Resolves an endpoint for a service and region combination.
:type service_name: string
:param service_name: Name of the service to resolve an endpoint for
(e.g., s3)
:type region_name: string
:param region_name: Region/endpoint name to resolve (e.g., us-east-1)
if no region is provided, the first found partition-wide e... | def construct_endpoint(self, service_name, region_name=None):
| raise NotImplementedError
|
'Lists the partitions available to the endpoint resolver.
:return: Returns a list of partition names (e.g., ["aws", "aws-cn"]).'
| def get_available_partitions(self):
| raise NotImplementedError
|
'Lists the endpoint names of a particular partition.
:type service_name: string
:param service_name: Name of a service to list endpoint for (e.g., s3)
:type partition_name: string
:param partition_name: Name of the partition to limit endpoints to.
(e.g., aws for the public AWS endpoints, aws-cn for AWS China
endpoints,... | def get_available_endpoints(self, service_name, partition_name='aws', allow_non_regional=False):
| raise NotImplementedError
|
':param endpoint_data: A dict of partition data.'
| def __init__(self, endpoint_data):
| if ('partitions' not in endpoint_data):
raise ValueError('Missing "partitions" in endpoint data')
self._endpoint_data = endpoint_data
|
'Warning: Using this property can lead to race conditions if you
access another property subsequently along the refresh boundary.
Please use get_frozen_credentials instead.'
| @property
def access_key(self):
| self._refresh()
return self._access_key
|
'Warning: Using this property can lead to race conditions if you
access another property subsequently along the refresh boundary.
Please use get_frozen_credentials instead.'
| @property
def secret_key(self):
| self._refresh()
return self._secret_key
|
'Warning: Using this property can lead to race conditions if you
access another property subsequently along the refresh boundary.
Please use get_frozen_credentials instead.'
| @property
def token(self):
| self._refresh()
return self._token
|
'Check if a refresh is needed.
A refresh is needed if the expiry time associated
with the temporary credentials is less than the
provided ``refresh_in``. If ``time_delta`` is not
provided, ``self.advisory_refresh_needed`` will be used.
For example, if your temporary credentials expire
in 10 minutes and the provided ``... | def refresh_needed(self, refresh_in=None):
| if (self._expiry_time is None):
return False
if (refresh_in is None):
refresh_in = self._advisory_refresh_timeout
if (self._seconds_remaining() >= refresh_in):
return False
logger.debug('Credentials need to be refreshed.')
return True
|
'Return immutable credentials.
The ``access_key``, ``secret_key``, and ``token`` properties
on this class will always check and refresh credentials if
needed before returning the particular credentials.
This has an edge case where you can get inconsistent
credentials. Imagine this:
# Current creds are "t1"
tmp.access_... | def get_frozen_credentials(self):
| self._refresh()
return self._frozen_credentials
|
'Loads the credentials from their source & sets them on the object.
Subclasses should implement this method (by reading from disk, the
environment, the network or wherever), returning ``True`` if they were
found & loaded.
If not found, this method should return ``False``, indictating that the
``CredentialResolver`` sho... | def load(self):
| return True
|
':param environ: The environment variables (defaults to
``os.environ`` if no value is provided).
:param mapping: An optional mapping of variable names to
environment variable names. Use this if you want to
change the mapping of access_key->AWS_ACCESS_KEY_ID, etc.
The dict can have up to 3 keys: ``access_key``, ``secre... | def __init__(self, environ=None, mapping=None):
| if (environ is None):
environ = os.environ
self.environ = environ
self._mapping = self._build_mapping(mapping)
|
'Search for credentials in explicit environment variables.'
| def load(self):
| if (self._mapping['access_key'] in self.environ):
logger.info('Found credentials in environment variables.')
fetcher = self._create_credentials_fetcher()
credentials = fetcher(require_expiry=False)
expiry_time = credentials['expiry_time']
if (expiry_time is not No... |
'Search for a credential file used by original EC2 CLI tools.'
| def load(self):
| if ('AWS_CREDENTIAL_FILE' in self._environ):
full_path = os.path.expanduser(self._environ['AWS_CREDENTIAL_FILE'])
creds = self._parser(full_path)
if (self.ACCESS_KEY in creds):
logger.info('Found credentials in AWS_CREDENTIAL_FILE.')
access_key = creds[self.A... |
':param config_filename: The session configuration scoped to the current
profile. This is available via ``session.config``.
:param profile_name: The name of the current profile.
:param config_parser: A config parser callable.'
| def __init__(self, config_filename, profile_name, config_parser=None):
| self._config_filename = config_filename
self._profile_name = profile_name
if (config_parser is None):
config_parser = botocore.configloader.load_config
self._config_parser = config_parser
|
'If there is are credentials in the configuration associated with
the session, use those.'
| def load(self):
| try:
full_config = self._config_parser(self._config_filename)
except ConfigNotFound:
return None
if (self._profile_name in full_config['profiles']):
profile_config = full_config['profiles'][self._profile_name]
if (self.ACCESS_KEY in profile_config):
logger.info('C... |
'Look for credentials in boto config file.'
| def load(self):
| if (self.BOTO_CONFIG_ENV in self._environ):
potential_locations = [self._environ[self.BOTO_CONFIG_ENV]]
else:
potential_locations = self.DEFAULT_CONFIG_FILENAMES
for filename in potential_locations:
try:
config = self._ini_parser(filename)
except ConfigNotFound:
... |
':type load_config: callable
:param load_config: A function that accepts no arguments, and
when called, will return the full configuration dictionary
for the session (``session.full_config``).
:type client_creator: callable
:param client_creator: A factory function that will create
a client when called. Has the same i... | def __init__(self, load_config, client_creator, cache, profile_name, prompter=getpass.getpass):
| self.cache = cache
self._load_config = load_config
self._client_creator = client_creator
self._profile_name = profile_name
self._prompter = prompter
self._loaded_config = {}
|
':param providers: A list of ``CredentialProvider`` instances.'
| def __init__(self, providers):
| self.providers = providers
|
'Inserts a new instance of ``CredentialProvider`` into the chain that
will be tried before an existing one.
:param name: The short name of the credentials you\'d like to insert the
new credentials before. (ex. ``env`` or ``config``). Existing names
& ordering can be discovered via ``self.available_methods``.
:type name... | def insert_before(self, name, credential_provider):
| try:
offset = [p.METHOD for p in self.providers].index(name)
except ValueError:
raise UnknownCredentialError(name=name)
self.providers.insert(offset, credential_provider)
|
'Inserts a new type of ``Credentials`` instance into the chain that will
be tried after an existing one.
:param name: The short name of the credentials you\'d like to insert the
new credentials after. (ex. ``env`` or ``config``). Existing names
& ordering can be discovered via ``self.available_methods``.
:type name: st... | def insert_after(self, name, credential_provider):
| offset = self._get_provider_offset(name)
self.providers.insert((offset + 1), credential_provider)
|
'Removes a given ``Credentials`` instance from the chain.
:param name: The short name of the credentials instance to remove.
:type name: string'
| def remove(self, name):
| available_methods = [p.METHOD for p in self.providers]
if (name not in available_methods):
return
offset = available_methods.index(name)
self.providers.pop(offset)
|
'Return a credential provider by name.
:type name: str
:param name: The name of the provider.
:raises UnknownCredentialError: Raised if no
credential provider by the provided name
is found.'
| def get_provider(self, name):
| return self.providers[self._get_provider_offset(name)]
|
'Goes through the credentials chain, returning the first ``Credentials``
that could be loaded.'
| def load_credentials(self):
| for provider in self.providers:
logger.debug('Looking for credentials via: %s', provider.METHOD)
creds = provider.load()
if (creds is not None):
return creds
return None
|
'Checks if the file exists.
:type file_path: str
:param file_path: The full path to the file to load without
the \'.json\' extension.
:return: True if file path exists, False otherwise.'
| def exists(self, file_path):
| return os.path.isfile((file_path + '.json'))
|
'Attempt to load the file path.
:type file_path: str
:param file_path: The full path to the file to load without
the \'.json\' extension.
:return: The loaded data if it exists, otherwise None.'
| def load_file(self, file_path):
| full_path = (file_path + '.json')
if (not os.path.isfile(full_path)):
return
with open(full_path, 'rb') as fp:
payload = fp.read().decode('utf-8')
logger.debug('Loading JSON file: %s', full_path)
return json.loads(payload, object_pairs_hook=OrderedDict)
|
'List all known services.
This will traverse the search path and look for all known
services.
:type type_name: str
:param type_name: The type of the service (service-2,
paginators-1, waiters-2, etc). This is needed because
the list of available services depends on the service
type. For example, the latest API version... | @instance_cache
def list_available_services(self, type_name):
| services = set()
for possible_path in self._potential_locations():
possible_services = [d for d in os.listdir(possible_path) if os.path.isdir(os.path.join(possible_path, d))]
for service_name in possible_services:
full_dirname = os.path.join(possible_path, service_name)
a... |
'Find the latest API version available for a service.
:type service_name: str
:param service_name: The name of the service.
:type type_name: str
:param type_name: The type of the service (service-2,
paginators-1, waiters-2, etc). This is needed because
the latest API version available can depend on the service
type. ... | @instance_cache
def determine_latest_version(self, service_name, type_name):
| return max(self.list_api_versions(service_name, type_name))
|
'List all API versions available for a particular service type
:type service_name: str
:param service_name: The name of the service
:type type_name: str
:param type_name: The type name for the service (i.e service-2,
paginators-1, etc.)
:rtype: list
:return: A list of API version strings in sorted order.'
| @instance_cache
def list_api_versions(self, service_name, type_name):
| known_api_versions = set()
for possible_path in self._potential_locations(service_name, must_exist=True, is_dir=True):
for dirname in os.listdir(possible_path):
full_path = os.path.join(possible_path, dirname, type_name)
if self.file_loader.exists(full_path):
know... |
'Load a botocore service model
This is the main method for loading botocore models (e.g. a service
model, pagination configs, waiter configs, etc.).
:type service_name: str
:param service_name: The name of the service (e.g ``ec2``, ``s3``).
:type type_name: str
:param type_name: The model type. Valid types include, bu... | @instance_cache
def load_service_model(self, service_name, type_name, api_version=None):
| known_services = self.list_available_services(type_name)
if (service_name not in known_services):
raise UnknownServiceError(service_name=service_name, known_service_names=', '.join(sorted(known_services)))
if (api_version is None):
api_version = self.determine_latest_version(service_name,... |
'Creates an iterator over all the extras data.'
| def _find_extras(self, service_name, type_name, api_version):
| for extras_type in self.extras_types:
extras_name = ('%s.%s-extras' % (type_name, extras_type))
full_path = os.path.join(service_name, api_version, extras_name)
try:
(yield self.load_data(full_path))
except DataNotFoundError:
pass
|
'Load data given a data path.
This is a low level method that will search through the various
search paths until it\'s able to load a value. This is typically
only needed to load *non* model files (such as _endpoints and
_retry). If you need to load model files, you should prefer
``load_service_model``.
:type name: s... | @instance_cache
def load_data(self, name):
| for possible_path in self._potential_locations(name):
found = self.file_loader.load_file(possible_path)
if (found is not None):
return found
raise DataNotFoundError(data_path=name)
|
'Processes data from a list of loaded extras files into a model
:type original_model: dict
:param original_model: The service model to load all the extras into.
:type extra_models: iterable of dict
:param extra_models: A list of loaded extras models.'
| def process(self, original_model, extra_models):
| for extras in extra_models:
self._process(original_model, extras)
|
'Process a single extras model into a service model.'
| def _process(self, model, extra_model):
| if ('merge' in extra_model):
deep_merge(model, extra_model['merge'])
|
':type shape_name: string
:param shape_name: The name of the shape.
:type shape_model: dict
:param shape_model: The shape model. This would be the value
associated with the key in the "shapes" dict of the
service model (i.e ``model[\'shapes\'][shape_name]``)
:type shape_resolver: botocore.model.ShapeResolver
:param sh... | def __init__(self, shape_name, shape_model, shape_resolver=None):
| self.name = shape_name
self.type_name = shape_model['type']
self.documentation = shape_model.get('documentation', '')
self._shape_model = shape_model
if (shape_resolver is None):
shape_resolver = UnresolvableShapeMap()
self._shape_resolver = shape_resolver
self._cache = {}
|
'Serialization information about the shape.
This contains information that may be needed for input serialization
or response parsing. This can include:
* name
* queryName
* flattened
* location
* payload
* streaming
* xmlNamespace
* resultWrapper
* xmlAttribute
* jsonvalue
:rtype: dict
:return: Serialization informati... | @CachedProperty
def serialization(self):
| model = self._shape_model
serialization = {}
for attr in self.SERIALIZED_ATTRS:
if (attr in self._shape_model):
serialization[attr] = model[attr]
if ('locationName' in serialization):
serialization['name'] = serialization.pop('locationName')
return serialization
|
'Metadata about the shape.
This requires optional information about the shape, including:
* min
* max
* enum
* sensitive
* required
* idempotencyToken
:rtype: dict
:return: Metadata about the shape.'
| @CachedProperty
def metadata(self):
| model = self._shape_model
metadata = {}
for attr in self.METADATA_ATTRS:
if (attr in self._shape_model):
metadata[attr] = model[attr]
return metadata
|
'A list of members that are required.
A structure shape can define members that are required.
This value will return a list of required members. If there
are no required members an empty list is returned.'
| @CachedProperty
def required_members(self):
| return self.metadata.get('required', [])
|
':type service_description: dict
:param service_description: The service description model. This value
is obtained from a botocore.loader.Loader, or from directly loading
the file yourself::
service_description = json.load(
open(\'/path/to/service-description-model.json\'))
model = ServiceModel(service_description)
:t... | def __init__(self, service_description, service_name=None):
| self._service_description = service_description
self.metadata = service_description.get('metadata', {})
self._shape_resolver = ShapeResolver(service_description.get('shapes', {}))
self._signature_version = NOT_SET
self._service_name = service_name
self._instance_cache = {}
|
'The name of the service.
This defaults to the endpointPrefix defined in the service model.
However, this value can be overriden when a ``ServiceModel`` is
created. If a service_name was not provided when the ``ServiceModel``
was created and if there is no endpointPrefix defined in the
service model, then an ``Undefin... | @CachedProperty
def service_name(self):
| if (self._service_name is not None):
return self._service_name
else:
return self.endpoint_prefix
|
'The name to use when computing signatures.
If the model does not define a signing name, this
value will be the endpoint prefix defined in the model.'
| @CachedProperty
def signing_name(self):
| signing_name = self.metadata.get('signingName')
if (signing_name is None):
signing_name = self.endpoint_prefix
return signing_name
|
':type operation_model: dict
:param operation_model: The operation model. This comes from the
service model, and is the value associated with the operation
name in the service model (i.e ``model[\'operations\'][op_name]``).
:type service_model: botocore.model.ServiceModel
:param service_model: The service model associ... | def __init__(self, operation_model, service_model, name=None):
| self._operation_model = operation_model
self._service_model = service_model
self._api_name = name
self._wire_name = operation_model.get('name')
self.metadata = service_model.metadata
self.http = operation_model.get('http', {})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.