desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Get a resource collection iterator from this manager.
:rtype: :py:class:`ResourceCollection`
:return: An iterable representing the collection of resources'
| def iterator(self, **kwargs):
| return self._collection_cls(self._model, self._parent, self._handler, **kwargs)
|
'Loads a collection from a model, creating a new
:py:class:`CollectionManager` subclass
with the correct properties and methods, named based on the service
and resource name, e.g. ec2.InstanceCollectionManager. It also
creates a new :py:class:`ResourceCollection` subclass which is used
by the new manager class.
:type r... | def load_from_definition(self, resource_name, collection_model, service_context, event_emitter):
| attrs = {}
collection_name = collection_model.name
self._load_batch_actions(attrs, resource_name, collection_model, service_context.service_model, event_emitter)
self._load_documented_collection_methods(attrs=attrs, resource_name=resource_name, collection_model=collection_model, service_model=service_co... |
'Batch actions on the collection become methods on both
the collection manager and iterators.'
| def _load_batch_actions(self, attrs, resource_name, collection_model, service_model, event_emitter):
| for action_model in collection_model.batch_actions:
snake_cased = xform_name(action_model.name)
attrs[snake_cased] = self._create_batch_action(resource_name, snake_cased, action_model, collection_model, service_model, event_emitter)
|
'Creates a new method which makes a batch operation request
to the underlying service API.'
| def _create_batch_action(factory_self, resource_name, snake_cased, action_model, collection_model, service_model, event_emitter):
| action = BatchAction(action_model)
def batch_action(self, *args, **kwargs):
return action(self, *args, **kwargs)
batch_action.__name__ = str(snake_cased)
batch_action.__doc__ = docstring.BatchActionDocstring(resource_name=resource_name, event_emitter=event_emitter, batch_action_model=action_mode... |
'Loads a resource from a model, creating a new
:py:class:`~boto3.resources.base.ServiceResource` subclass
with the correct properties and methods, named based on the service
and resource name, e.g. EC2.Instance.
:type resource_name: string
:param resource_name: Name of the resource to look up. For services,
this should... | def load_from_definition(self, resource_name, single_resource_json_definition, service_context):
| logger.debug('Loading %s:%s', service_context.service_name, resource_name)
resource_model = ResourceModel(resource_name, single_resource_json_definition, service_context.resource_json_definitions)
shape = None
if resource_model.shape:
shape = service_context.service_model.shape_for(resource_m... |
'Populate required identifiers. These are arguments without which
the resource cannot be used. Identifiers become arguments for
operations on the resource.'
| def _load_identifiers(self, attrs, meta, resource_model, resource_name):
| for identifier in resource_model.identifiers:
meta.identifiers.append(identifier.name)
attrs[identifier.name] = self._create_identifier(identifier, resource_name)
|
'Actions on the resource become methods, with the ``load`` method
being a special case which sets internal data for attributes, and
``reload`` is an alias for ``load``.'
| def _load_actions(self, attrs, resource_name, resource_model, service_context):
| if resource_model.load:
attrs['load'] = self._create_action(action_model=resource_model.load, resource_name=resource_name, service_context=service_context, is_load=True)
attrs['reload'] = attrs['load']
for action in resource_model.actions:
attrs[action.name] = self._create_action(action_... |
'Load resource attributes based on the resource shape. The shape
name is referenced in the resource JSON, but the shape itself
is defined in the Botocore service JSON, hence the need for
access to the ``service_model``.'
| def _load_attributes(self, attrs, meta, resource_name, resource_model, service_context):
| if (not resource_model.shape):
return
shape = service_context.service_model.shape_for(resource_model.shape)
identifiers = dict(((i.member_name, i) for i in resource_model.identifiers if i.member_name))
attributes = resource_model.get_attributes(shape)
for (name, (orig_name, member)) in attri... |
'Load resource collections from the model. Each collection becomes
a :py:class:`~boto3.resources.collection.CollectionManager` instance
on the resource instance, which allows you to iterate and filter
through the collection\'s items.'
| def _load_collections(self, attrs, resource_model, service_context):
| for collection_model in resource_model.collections:
attrs[collection_model.name] = self._create_collection(resource_name=resource_model.name, collection_model=collection_model, service_context=service_context)
|
'Load related resources, which are defined via a ``has``
relationship but conceptually come in two forms:
1. A reference, which is a related resource instance and can be
``None``, such as an EC2 instance\'s ``vpc``.
2. A subresource, which is a resource constructor that will always
return a resource instance which shar... | def _load_has_relations(self, attrs, resource_name, resource_model, service_context):
| for reference in resource_model.references:
attrs[reference.name] = self._create_reference(reference_model=reference, resource_name=resource_name, service_context=service_context)
for subresource in resource_model.subresources:
attrs[subresource.name] = self._create_class_partial(subresource_mod... |
'Load resource waiters from the model. Each waiter allows you to
wait until a resource reaches a specific state by polling the state
of the resource.'
| def _load_waiters(self, attrs, resource_name, resource_model, service_context):
| for waiter in resource_model.waiters:
attrs[waiter.name] = self._create_waiter(resource_waiter_model=waiter, resource_name=resource_name, service_context=service_context)
|
'Creates a read-only property for identifier attributes.'
| def _create_identifier(factory_self, identifier, resource_name):
| def get_identifier(self):
return getattr(self, ('_' + identifier.name), None)
get_identifier.__name__ = str(identifier.name)
get_identifier.__doc__ = docstring.IdentifierDocstring(resource_name=resource_name, identifier_model=identifier, include_signature=False)
return property(get_identifier)
|
'Creates a read-only property that aliases an identifier.'
| def _create_identifier_alias(factory_self, resource_name, identifier, member_model, service_context):
| def get_identifier(self):
return getattr(self, ('_' + identifier.name), None)
get_identifier.__name__ = str(identifier.member_name)
get_identifier.__doc__ = docstring.AttributeDocstring(service_name=service_context.service_name, resource_name=resource_name, attr_name=identifier.member_name, event_em... |
'Creates a new property on the resource to lazy-load its value
via the resource\'s ``load`` method (if it exists).'
| def _create_autoload_property(factory_self, resource_name, name, snake_cased, member_model, service_context):
| def property_loader(self):
if (self.meta.data is None):
if hasattr(self, 'load'):
self.load()
else:
raise ResourceLoadException('{0} has no load method'.format(self.__class__.__name__))
return self.meta.data.get(name)
property_l... |
'Creates a new wait method for each resource where both a waiter and
resource model is defined.'
| def _create_waiter(factory_self, resource_waiter_model, resource_name, service_context):
| waiter = WaiterAction(resource_waiter_model, waiter_resource_name=resource_waiter_model.name)
def do_waiter(self, *args, **kwargs):
waiter(self, *args, **kwargs)
do_waiter.__name__ = str(resource_waiter_model.name)
do_waiter.__doc__ = docstring.ResourceWaiterDocstring(resource_name=resource_name... |
'Creates a new property on the resource to lazy-load a collection.'
| def _create_collection(factory_self, resource_name, collection_model, service_context):
| cls = factory_self._collection_factory.load_from_definition(resource_name=resource_name, collection_model=collection_model, service_context=service_context, event_emitter=factory_self._emitter)
def get_collection(self):
return cls(collection_model=collection_model, parent=self, factory=factory_self, ser... |
'Creates a new property on the resource to lazy-load a reference.'
| def _create_reference(factory_self, reference_model, resource_name, service_context):
| handler = ResourceHandler(search_path=reference_model.resource.path, factory=factory_self, resource_model=reference_model.resource, service_context=service_context)
needs_data = any(((i.source == 'data') for i in reference_model.resource.identifiers))
def get_reference(self):
if (needs_data and (sel... |
'Creates a new method which acts as a functools.partial, passing
along the instance\'s low-level `client` to the new resource
class\' constructor.'
| def _create_class_partial(factory_self, subresource_model, resource_name, service_context):
| name = subresource_model.resource.type
def create_resource(self, *args, **kwargs):
positional_args = []
json_def = service_context.resource_json_definitions.get(name, {})
resource_cls = factory_self.load_from_definition(resource_name=name, single_resource_json_definition=json_def, servic... |
'Creates a new method which makes a request to the underlying
AWS service.'
| def _create_action(factory_self, action_model, resource_name, service_context, is_load=False):
| action = ServiceAction(action_model, factory=factory_self, service_context=service_context)
if is_load:
def do_action(self, *args, **kwargs):
response = action(self, *args, **kwargs)
self.meta.data = response
lazy_docstring = docstring.LoadReloadDocstring(action_name=acti... |
'Perform the action\'s request operation after building operation
parameters and build any defined resources from the response.
:type parent: :py:class:`~boto3.resources.base.ServiceResource`
:param parent: The resource instance to which this action is attached.
:rtype: dict or ServiceResource or list(ServiceResource)
... | def __call__(self, parent, *args, **kwargs):
| operation_name = xform_name(self._action_model.request.operation)
params = create_request_parameters(parent, self._action_model.request)
params.update(kwargs)
logger.debug('Calling %s:%s with %r', parent.meta.service_name, operation_name, params)
response = getattr(parent.meta.client, opera... |
'Perform the batch action\'s operation on every page of results
from the collection.
:type parent:
:py:class:`~boto3.resources.collection.ResourceCollection`
:param parent: The collection iterator to which this action
is attached.
:rtype: list(dict)
:return: A list of low-level response dicts from each call.'
| def __call__(self, parent, *args, **kwargs):
| service_name = None
client = None
responses = []
operation_name = xform_name(self._action_model.request.operation)
for page in parent.pages():
params = {}
for (index, resource) in enumerate(page):
if (service_name is None):
service_name = resource.meta.ser... |
'Perform the wait operation after building operation
parameters.
:type parent: :py:class:`~boto3.resources.base.ServiceResource`
:param parent: The resource instance to which this action is attached.'
| def __call__(self, parent, *args, **kwargs):
| client_waiter_name = xform_name(self._waiter_model.waiter_name)
params = create_request_parameters(parent, self._waiter_model)
params.update(kwargs)
logger.debug('Calling %s:%s with %r', parent.meta.service_name, self._waiter_resource_name, params)
client = parent.meta.client
waiter = c... |
':type action_name: str
:param action_name: The name of the action to inject, e.g.
\'delete_tags\'
:type action_model: dict
:param action_model: A JSON definition of the action, as if it were
part of the resource model.
:type function: function
:param function: The function to perform when the action is called.
The fir... | def __init__(self, action_name, action_model, function, event_emitter):
| self.name = action_name
self.model = action_model
self.function = function
self.emitter = event_emitter
|
'Get a list of auto-filled parameters for this request.
:type: list(:py:class:`Parameter`)'
| @property
def params(self):
| params = []
for item in self._definition.get('params', []):
params.append(Parameter(**item))
return params
|
'A list of resource identifiers.
:type: list(:py:class:`Identifier`)'
| @property
def identifiers(self):
| identifiers = []
for item in self._definition.get('identifiers', []):
identifiers.append(Parameter(**item))
return identifiers
|
'Get the resource model for the response resource.
:type: :py:class:`ResourceModel`'
| @property
def model(self):
| return ResourceModel(self.type, self._resource_defs[self.type], self._resource_defs)
|
'Get a list of batch actions supported by the resource type
contained in this action. This is a shortcut for accessing
the same information through the resource model.
:rtype: list(:py:class:`Action`)'
| @property
def batch_actions(self):
| return self.resource.model.batch_actions
|
'Load a name translation map given a shape. This will set
up renamed values for any collisions, e.g. if the shape,
an action, and a subresource all are all named ``foo``
then the resource will have an action ``foo``, a subresource
named ``Foo`` and a property named ``foo_attribute``.
This is the order of precedence, fr... | def load_rename_map(self, shape=None):
| names = set(['meta'])
self._renamed = {}
if self._definition.get('load'):
names.add('load')
for item in self._definition.get('identifiers', []):
self._load_name_with_category(names, item['name'], 'identifier')
for name in self._definition.get('actions', {}):
self._load_name_w... |
'Load a name with a given category, possibly renaming it
if that name is already in use. The name will be stored
in ``names`` and possibly be set up in ``self._renamed``.
:type names: set
:param names: Existing names (Python attributes, properties, or
methods) on the resource.
:type name: string
:param name: The origin... | def _load_name_with_category(self, names, name, category, snake_case=True):
| if snake_case:
name = xform_name(name)
if (name in names):
logger.debug(('Renaming %s %s %s' % (self.name, category, name)))
self._renamed[(category, name)] = ((name + '_') + category)
name += ('_' + category)
if (name in names):
raise ValueError('Pro... |
'Get a possibly renamed value given a category and name. This
uses the rename map set up in ``load_rename_map``, so that
method must be called once first.
:type category: string
:param category: The value type, such as \'identifier\' or \'action\'
:type name: string
:param name: The original name of the value
:type sna... | def _get_name(self, category, name, snake_case=True):
| if snake_case:
name = xform_name(name)
return self._renamed.get((category, name), name)
|
'Get a dictionary of attribute names to original name and shape
models that represent the attributes of this resource. Looks
like the following:
\'some_name\': (\'SomeName\', <Shape...>)
:type shape: botocore.model.Shape
:param shape: The underlying shape for this resource.
:rtype: dict
:return: Mapping of resource att... | def get_attributes(self, shape):
| attributes = {}
identifier_names = [i.name for i in self.identifiers]
for (name, member) in shape.members.items():
snake_cased = xform_name(name)
if (snake_cased in identifier_names):
continue
snake_cased = self._get_name('attribute', snake_cased, snake_case=False)
... |
'Get a list of resource identifiers.
:type: list(:py:class:`Identifier`)'
| @property
def identifiers(self):
| identifiers = []
for item in self._definition.get('identifiers', []):
name = self._get_name('identifier', item['name'])
member_name = item.get('memberName', None)
if member_name:
member_name = self._get_name('attribute', member_name)
identifiers.append(Identifier(name... |
'Get the load action for this resource, if it is defined.
:type: :py:class:`Action` or ``None``'
| @property
def load(self):
| action = self._definition.get('load')
if (action is not None):
action = Action('load', action, self._resource_defs)
return action
|
'Get a list of actions for this resource.
:type: list(:py:class:`Action`)'
| @property
def actions(self):
| actions = []
for (name, item) in self._definition.get('actions', {}).items():
name = self._get_name('action', name)
actions.append(Action(name, item, self._resource_defs))
return actions
|
'Get a list of batch actions for this resource.
:type: list(:py:class:`Action`)'
| @property
def batch_actions(self):
| actions = []
for (name, item) in self._definition.get('batchActions', {}).items():
name = self._get_name('batch_action', name)
actions.append(Action(name, item, self._resource_defs))
return actions
|
'Get a ``has`` relationship definition from a model, where the
service resource model is treated special in that it contains
a relationship to every resource defined for the service. This
allows things like ``s3.Object(\'bucket-name\', \'key\')`` to
work even though the JSON doesn\'t define it explicitly.
:rtype: dict
... | def _get_has_definition(self):
| if (self.name not in self._resource_defs):
definition = {}
for (name, resource_def) in self._resource_defs.items():
found = False
has_items = self._definition.get('has', {}).items()
for (has_name, has_def) in has_items:
if (has_def.get('resource', ... |
'Get a list of sub-resources or references.
:type subresources: bool
:param subresources: ``True`` to get sub-resources, ``False`` to
get references.
:rtype: list(:py:class:`ResponseResource`)'
| def _get_related_resources(self, subresources):
| resources = []
for (name, definition) in self._get_has_definition().items():
if subresources:
name = self._get_name('subresource', name, snake_case=False)
else:
name = self._get_name('reference', name)
action = Action(name, definition, self._resource_defs)
... |
'Get a list of sub-resources.
:type: list(:py:class`ResponseResource`)'
| @property
def subresources(self):
| return self._get_related_resources(True)
|
'Get a list of reference resources.
:type: list(:py:class:`ResponseResource`)'
| @property
def references(self):
| return self._get_related_resources(False)
|
'Get a list of collections for this resource.
:type: list(:py:class:`Collection`)'
| @property
def collections(self):
| collections = []
for (name, item) in self._definition.get('hasMany', {}).items():
name = self._get_name('collection', name)
collections.append(Collection(name, item, self._resource_defs))
return collections
|
'Get a list of waiters for this resource.
:type: list(:py:class:`Waiter`)'
| @property
def waiters(self):
| waiters = []
for (name, item) in self._definition.get('waiters', {}).items():
name = self._get_name('waiter', (Waiter.PREFIX + name))
waiters.append(Waiter(name, item))
return waiters
|
'Create a batch writer object.
This method creates a context manager for writing
objects to Amazon DynamoDB in batch.
The batch writer will automatically handle buffering and sending items
in batches. In addition, the batch writer will also automatically
handle any unprocessed items and resend them as needed. All you... | def batch_writer(self, overwrite_by_pkeys=None):
| return BatchWriter(self.name, self.meta.client, overwrite_by_pkeys=overwrite_by_pkeys)
|
':type table_name: str
:param table_name: The name of the table. The class handles
batch writes to a single table.
:type client: ``botocore.client.Client``
:param client: A botocore client. Note this client
**must** have the dynamodb customizations applied
to it for transforming AttributeValues into the
wire protocol... | def __init__(self, table_name, client, flush_amount=25, overwrite_by_pkeys=None):
| self._table_name = table_name
self._client = client
self._items_buffer = []
self._flush_amount = flush_amount
self._overwrite_by_pkeys = overwrite_by_pkeys
|
'Creates a condition where the attribute is equal to the value.
:param value: The value that the attribute is equal to.'
| def eq(self, value):
| return Equals(self, value)
|
'Creates a condition where the attribute is less than the value.
:param value: The value that the attribute is less than.'
| def lt(self, value):
| return LessThan(self, value)
|
'Creates a condition where the attribute is less than or equal to the
value.
:param value: The value that the attribute is less than or equal to.'
| def lte(self, value):
| return LessThanEquals(self, value)
|
'Creates a condition where the attribute is greater than the value.
:param value: The value that the attribute is greater than.'
| def gt(self, value):
| return GreaterThan(self, value)
|
'Creates a condition where the attribute is greater than or equal to
the value.
:param value: The value that the attribute is greater than or equal to.'
| def gte(self, value):
| return GreaterThanEquals(self, value)
|
'Creates a condition where the attribute begins with the value.
:param value: The value that the attribute begins with.'
| def begins_with(self, value):
| return BeginsWith(self, value)
|
'Creates a condition where the attribute is greater than or equal
to the low value and less than or equal to the high value.
:param low_value: The value that the attribute is greater than.
:param high_value: The value that the attribute is less than.'
| def between(self, low_value, high_value):
| return Between(self, low_value, high_value)
|
'Creates a condition where the attribute is not equal to the value
:param value: The value that the attribute is not equal to.'
| def ne(self, value):
| return NotEquals(self, value)
|
'Creates a condition where the attribute is in the value,
:type value: list
:param value: The value that the attribute is in.'
| def is_in(self, value):
| return In(self, value)
|
'Creates a condition where the attribute exists.'
| def exists(self):
| return AttributeExists(self)
|
'Creates a condition where the attribute does not exist.'
| def not_exists(self):
| return AttributeNotExists(self)
|
'Creates a condition where the attribute contains the value.
:param value: The value the attribute contains.'
| def contains(self, value):
| return Contains(self, value)
|
'Creates a condition for the attribute size.
Note another AttributeBase method must be called on the returned
size condition to be a valid DynamoDB condition.'
| def size(self):
| return Size(self)
|
'Creates a condition for the attribute type.
:param value: The type of the attribute.'
| def attribute_type(self, value):
| return AttributeType(self, value)
|
'Resets the placeholder name and values'
| def reset(self):
| self._name_count = 0
self._value_count = 0
|
'Builds the condition expression and the dictionary of placeholders.
:type condition: ConditionBase
:param condition: A condition to be built into a condition expression
string with any necessary placeholders.
:type is_key_condition: Boolean
:param is_key_condition: True if the expression is for a
KeyConditionExpressio... | def build_expression(self, condition, is_key_condition=False):
| if (not isinstance(condition, ConditionBase)):
raise DynamoDBNeedsConditionError(condition)
attribute_name_placeholders = {}
attribute_value_placeholders = {}
condition_expression = self._build_expression(condition, attribute_name_placeholders, attribute_value_placeholders, is_key_condition=is_k... |
'Injects the condition expression transformation into the parameters
This injection includes transformations for ConditionExpression shapes
and KeyExpression shapes. It also handles any placeholder names and
values that are generated when transforming the condition expressions.'
| def inject_condition_expressions(self, params, model, **kwargs):
| self._condition_builder.reset()
generated_names = {}
generated_values = {}
transformation = ConditionExpressionTransformation(self._condition_builder, placeholder_names=generated_names, placeholder_values=generated_values, is_key_condition=False)
self._transformer.transform(params, model.input_shape... |
'Injects DynamoDB serialization into parameter input'
| def inject_attribute_value_input(self, params, model, **kwargs):
| self._transformer.transform(params, model.input_shape, self._serializer.serialize, 'AttributeValue')
|
'Injects DynamoDB deserialization into responses'
| def inject_attribute_value_output(self, parsed, model, **kwargs):
| self._transformer.transform(parsed, model.output_shape, self._deserializer.deserialize, 'AttributeValue')
|
'Transforms the dynamodb input to or output from botocore
It applies a specified transformation whenever a specific shape name
is encountered while traversing the parameters in the dictionary.
:param params: The parameters structure to transform.
:param model: The operation model.
:param transformation: The function to... | def transform(self, params, model, transformation, target_shape):
| self._transform_parameters(model, params, transformation, target_shape)
|
'The method to serialize the Python data types.
:param value: A python value to be serialized to DynamoDB. Here are
the various conversions:
Python DynamoDB
None {\'NULL\': True}
True/False {\'BOOL\': True/False}
int/Decima... | def serialize(self, value):
| dynamodb_type = self._get_dynamodb_type(value)
serializer = getattr(self, ('_serialize_%s' % dynamodb_type.lower()))
return {dynamodb_type: serializer(value)}
|
'The method to deserialize the DynamoDB data types.
:param value: A DynamoDB value to be deserialized to a pythonic value.
Here are the various conversions:
DynamoDB Python
{\'NULL\': True} None
{\'BOOL\': True/False} True/False
{\'N\': str(valu... | def deserialize(self, value):
| if (not value):
raise TypeError('Value must be a nonempty dictionary whose key is a valid dynamodb type.')
dynamodb_type = list(value.keys())[0]
try:
deserializer = getattr(self, ('_deserialize_%s' % dynamodb_type.lower()))
except AttributeError:
... |
'Create a new session with the given arguments. Additionally,
this method will set the credentials file to the test credentials
used by the following test cases.'
| def create_session(self, *args, **kwargs):
| kwargs['session_vars'] = {'credentials_file': (None, None, os.path.join(os.path.dirname(__file__), 'test-credentials'), None)}
return Session(*args, **kwargs)
|
'Test that InstanceExists can handle a nonexistent instance.'
| def test_dont_search_on_error_responses(self):
| waiter = self.client.get_waiter('instance_exists')
waiter.config.max_attempts = 1
with self.assertRaises(WaiterError):
waiter.wait(InstanceIds=['i-12345'])
|
'Start up the command runner process.'
| def start(self, env=None):
| self._popen = Popen([sys.executable, self.CLIENT_SERVER], stdout=PIPE, stdin=PIPE, env=env)
|
'Shutdown the command runner process.'
| def stop(self):
| self.cmd('exit')
self._popen.wait()
|
'Send a command and return immediately.
This is a lower level method than cmd().
This method will instruct the cmd-runner process
to execute a command, but this method will
immediately return. You will need to use
``is_cmd_finished()`` to check that the command
is finished.
This method is useful if you want to record ... | def send_cmd(self, *cmd):
| cmd_str = (' '.join(cmd) + '\n')
cmd_bytes = cmd_str.encode('utf-8')
self._popen.stdin.write(cmd_bytes)
self._popen.stdin.flush()
|
'Send a command and block until it finishes.
This method will send a command to the cmd-runner process
to run. It will block until the cmd-runner process is
finished executing the command and sends back a status
response.'
| def cmd(self, *cmd):
| self.send_cmd(*cmd)
result = self._popen.stdout.readline().strip()
if (result != 'OK'):
raise RuntimeError(("Error from command '%s': %s" % (cmd, result)))
|
'Compares two parsed service responses. For ResponseMetadata, it will
only assert that the expected is a proper subset of the actual. This
is useful so that when new keys are added to the metadata, tests don\'t
break.'
| def assert_response_with_subset_metadata(self, actual_response, expected_response):
| actual = copy.copy(actual_response)
expected = copy.copy(expected_response)
actual_metadata = actual.pop('ResponseMetadata', {})
expected_metadata = expected.pop('ResponseMetadata', {})
self.assertEqual(actual, expected)
self.assert_dict_is_proper_subset(actual_metadata, expected_metadata)
|
'Asserts that a dictionary is a proper subset of another.'
| def assert_dict_is_proper_subset(self, superset, subset):
| self.assertTrue(all((((k in superset) and (superset[k] == v)) for (k, v) in subset.items())))
|
'Get the waiter model for the service.'
| def get_waiter_model(self, service, api_version=None):
| with mock.patch('botocore.loaders.Loader.list_available_services', return_value=[service]):
return WaiterModel(self.loader.load_service_model(service, type_name='waiters-2', api_version=api_version))
|
'Get the service model for the service.'
| def get_service_model(self, service, api_version=None):
| with mock.patch('botocore.loaders.Loader.list_available_services', return_value=[service]):
return ServiceModel(self.loader.load_service_model(service, type_name='service-2', api_version=api_version), service_name=service)
|
'This is a custom method
:type foo: string
:param foo: The foo parameter'
| def custom_method(self, foo):
| pass
|
'Set default arguments when a parser instance is created.
You can specify any kwargs that are allowed by a ResponseParser
class. There are currently two arguments:
* timestamp_parser - A callable that can parse a timetsamp string
* blob_parser - A callable that can parse a blob type'
| def set_parser_defaults(self, **kwargs):
| self._defaults.update(kwargs)
|
'Parse the HTTP response given a shape.
:param response: The HTTP response dictionary. This is a dictionary
that represents the HTTP request. The dictionary must have the
following keys, ``body``, ``headers``, and ``status_code``.
:param shape: The model shape describing the expected output.
:return: Returns a dictio... | def parse(self, response, shape):
| LOG.debug('Response headers: %s', response['headers'])
LOG.debug('Response body:\n%s', response['body'])
if (response['status_code'] >= 301):
if self._is_generic_error_response(response):
parsed = self._do_generic_error_parse(response)
else:
parsed = self._do... |
'Merges the config object with another config object
This will merge in all non-default values from the provided config
and return a new config object
:type other_config: botocore.config.Config
:param other config: Another config object to merge with. The values
in the provided config object will take precedence in the... | def merge(self, other_config):
| config_options = copy.copy(self._user_provided_options)
config_options.update(other_config._user_provided_options)
return Config(**config_options)
|
'Generate a sample input.
:type shape: ``botocore.model.Shape``
:param shape: The input shape.
:return: The generated skeleton input corresponding to the
provided input shape.'
| def generate_skeleton(self, shape):
| stack = []
return self._generate_skeleton(shape, stack)
|
'An S3 request sent to the wrong region will return an error that
contains the endpoint the request should be sent to. This handler
will add the redirect information to the signing context and then
redirect the request.'
| def redirect_from_error(self, request_dict, response, operation, **kwargs):
| if (response is None):
return
error = response[1].get('Error', {})
error_code = error.get('Code')
if (error_code == '301'):
if (operation.name not in ['HeadObject', 'HeadBucket']):
return
elif (error_code != 'PermanentRedirect'):
return
bucket = request_dict['... |
'There are multiple potential sources for the new region to redirect to,
but they aren\'t all universally available for use. This will try to
find region from response elements, but will fall back to calling
HEAD on the bucket if all else fails.
:param bucket: The bucket to find the region for. This is necessary if
the... | def get_bucket_region(self, bucket, response):
| service_response = response[1]
response_headers = service_response['ResponseMetadata']['HTTPHeaders']
if ('x-amz-bucket-region' in response_headers):
return response_headers['x-amz-bucket-region']
region = service_response.get('Error', {}).get('Region', None)
if (region is not None):
... |
'This handler retrieves a given bucket\'s signing context from the cache
and adds it into the request context.'
| def redirect_from_cache(self, params, context, **kwargs):
| bucket = params.get('Bucket')
signing_context = self._cache.get(bucket)
if (signing_context is not None):
context['signing'] = signing_context
else:
context['signing'] = {'bucket': bucket}
|
'Retrieve JSON metadata from container metadata.
:type full_url: str
:param full_url: The full URL of the metadata service.
This should include the scheme as well, e.g
"http://localhost:123/foo"'
| def retrieve_full_uri(self, full_url, headers=None):
| self._validate_allowed_url(full_url)
return self._retrieve_credentials(full_url, headers)
|
'Retrieve JSON metadata from ECS metadata.
:type relative_uri: str
:param relative_uri: A relative URI, e.g "/foo/bar?id=123"
:return: The parsed JSON response.'
| def retrieve_uri(self, relative_uri):
| full_url = self.full_url(relative_uri)
return self._retrieve_credentials(full_url)
|
'Set the timeout seconds on the socket.'
| def set_socket_timeout(self, timeout):
| try:
set_socket_timeout(self._raw_stream, timeout)
except AttributeError:
logger.error("Cannot access the socket object of a streaming response. It's possible the interface has changed.", exc_info=True)
raise
|
'Read at most amt bytes from the stream.
If the amt argument is omitted, read all data.'
| def read(self, amt=None):
| chunk = self._raw_stream.read(amt)
self._amount_read += len(chunk)
if ((not chunk) or (amt is None)):
self._verify_content_length()
return chunk
|
'Close the underlying http response stream.'
| def close(self):
| self._raw_stream.close()
|
'Base class for exceptions object on a client
:type code_to_exception: dict
:param code_to_exception: Mapping of error codes (strings) to exception
class that should be raised when encountering a particular
error code.'
| def __init__(self, code_to_exception):
| self._code_to_exception = code_to_exception
|
'Retrieves the error class based on the error code
This is helpful for identifying the exception class needing to be
caught based on the ClientError.parsed_reponse[\'Error\'][\'Code\'] value
:type error_code: string
:param error_code: The error code associated to a ClientError exception
:rtype: ClientError or a subclas... | def from_code(self, error_code):
| return self._code_to_exception.get(error_code, self.ClientError)
|
'Creates a ClientExceptions object for the particular service client
:type service_model: botocore.model.ServiceModel
:param service_model: The service model for the client
:rtype: object that subclasses from BaseClientExceptions
:returns: The exceptions object of a client that can be used
to grab the various different... | def create_client_exceptions(self, service_model):
| service_name = service_model.service_name
if (service_name not in self._client_exceptions_cache):
client_exceptions = self._create_client_exceptions(service_model)
self._client_exceptions_cache[service_name] = client_exceptions
return self._client_exceptions_cache[service_name]
|
'Handler for a retry.
Intended to be hooked up to an event handler (hence the **kwargs),
this will process retries appropriately.'
| def __call__(self, attempts, response, caught_exception, **kwargs):
| if self._checker(attempts, response, caught_exception):
result = self._action(attempts=attempts)
logger.debug('Retry needed, action of: %s', result)
return result
logger.debug('No retry needed.')
|
'Determine if retry criteria matches.
Note that either ``response`` is not None and ``caught_exception`` is
None or ``response`` is None and ``caught_exception`` is not None.
:type attempt_number: int
:param attempt_number: The total number of times we\'ve attempted
to send the request.
:param response: The HTTP respon... | def __call__(self, attempt_number, response, caught_exception):
| if (response is not None):
return self._check_response(attempt_number, response)
elif (caught_exception is not None):
return self._check_caught_exception(attempt_number, caught_exception)
else:
raise ValueError('Both response and caught_exception are None.')
|
'Serialize parameters into an HTTP request.
This method takes user provided parameters and a shape
model and serializes the parameters to an HTTP request.
More specifically, this method returns information about
parts of the HTTP request, it does not enforce a particular
interface or standard for an HTTP request. It i... | def serialize_to_request(self, parameters, operation_model):
| raise NotImplementedError('serialize_to_request')
|
'Aliases a non-extant method to an existing method.
:param actual_name: The name of the method that actually exists on
the client.'
| def __init__(self, actual_name):
| self._actual = actual_name
|
':param client: The client to add your stubs to.'
| def __init__(self, client):
| self.client = client
self._event_id = 'boto_stubber'
self._expected_params_event_id = 'boto_stubber_expected_params'
self._queue = deque()
|
'Activates the stubber on the client'
| def activate(self):
| self.client.meta.events.register_first('before-parameter-build.*.*', self._assert_expected_params, unique_id=self._expected_params_event_id)
self.client.meta.events.register('before-call.*.*', self._get_response_handler, unique_id=self._event_id)
|
'Deactivates the stubber on the client'
| def deactivate(self):
| self.client.meta.events.unregister('before-parameter-build.*.*', self._assert_expected_params, unique_id=self._expected_params_event_id)
self.client.meta.events.unregister('before-call.*.*', self._get_response_handler, unique_id=self._event_id)
|
'Adds a service response to the response queue. This will be validated
against the service model to ensure correctness. It should be noted,
however, that while missing attributes are often considered correct,
your code may not function properly if you leave them out. Therefore
you should always fill in every value you ... | def add_response(self, method, service_response, expected_params=None):
| self._add_response(method, service_response, expected_params)
|
'Adds a ``ClientError`` to the response queue.
:param method: The name of the service method to return the error on.
:type method: str
:param service_error_code: The service error code to return,
e.g. ``NoSuchBucket``
:type service_error_code: str
:param service_message: The service message to return, e.g.
\'The specif... | def add_client_error(self, method, service_error_code='', service_message='', http_status_code=400, service_error_meta=None, expected_params=None):
| http_response = Response()
http_response.status_code = http_status_code
parsed_response = {'ResponseMetadata': {'HTTPStatusCode': http_status_code}, 'Error': {'Message': service_message, 'Code': service_error_code}}
if (service_error_meta is not None):
parsed_response['Error'].update(service_err... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.