CustomRefreshableSession#
- class boto3_refresh_session.methods.custom.CustomRefreshableSession[source]#
A
boto3.session.Sessionobject that automatically refreshes temporary credentials returned by a custom credential getter provided by the user. Useful for users with highly sophisticated or idiosyncratic authentication flows.- Parameters:
- custom_credentials_methodCallable[…, TemporaryCredentials | Dict[str, str]]
Required. Accepts a callable object that returns temporary AWS security credentials. That object must return a dictionary containing ‘access_key’, ‘secret_key’, ‘token’, and ‘expiry_time’ when called.
- custom_credentials_method_argsDict[str, Any], optional
Optional keyword arguments for the function passed to the
custom_credentials_methodparameter.- defer_refreshbool = True, optional
If
Truethen temporary credentials are not automatically refreshed until they are explicitly needed. IfFalsethen temporary credentials refresh immediately upon expiration. It is highly recommended that you useTrue. Default isTrue.- advisory_timeoutint = 900, optional
USE THIS ARGUMENT WITH CAUTION!!!
Botocore will attempt to refresh credentials early according to this value (in seconds), but will continue using the existing credentials if refresh fails. Default is 15 minutes (900 seconds).
- mandatory_timeoutint = 600, optional
USE THIS ARGUMENT WITH CAUTION!!!
Botocore requires a successful refresh before continuing. If refresh fails in this window (in seconds), API calls may fail. Default is 10 minutes (600 seconds).
Attributes
The current temporary AWS security credentials.
cache
(SessionCache) The client and resource cache used to store and retrieve cached clients.
Methods
client(*args, eviction_policy: EvictionPolicy, max_size: int, **kwargs) -> BaseClient
Creates a low-level service client by name.
get_identity() -> Identity
Returns metadata about the current caller identity.
refreshable_credentials() -> TemporaryCredentials
Returns the current temporary AWS security credentials.
resource(*args, eviction_policy: EvictionPolicy, max_size: int, **kwargs) -> ServiceResource
Creates a low-level service resource by name.
whoami() -> Identity
Alias for
get_identity.- Other Parameters:
- **kwargsAny, optional
Optional keyword arguments for the
boto3.session.Sessionobject.
- Raises:
- BRSValidationError
If the provided parameters are of incorrect types or if required parameters are missing.
- BRSCredentialError
If the credentials returned by the custom credential getter are missing required key-value pairs or if ‘expiry_time’ is not a valid ISO 8601 string or datetime object.
Notes
Important
custom_credentials_methodmust be a callable object that returns temporary AWS credentials when called. The returned credentials must be a dictionary (cast asTemporaryCredentials) containing the following key-value pairs: access_key (str), secret_key (str), token (str), and expiry_time (str in ISO 8601 format or datetime object).Tip
You can import
TemporaryCredentialsfromboto3_refresh_session.utils.typing.TemporaryCredentials. To avoid typing warnings in your IDE, you may want to cast the dict returned by your custom credential getter asTemporaryCredentials.Examples
Write (or import) the callable object for obtaining temporary AWS security credentials.
>>> def your_custom_credential_getter(your_param, another_param): >>> ... >>> return { >>> 'access_key': '...', >>> 'secret_key': '...', >>> 'token': '...', >>> 'expiry_time': '...', >>> }
Pass that callable object to
RefreshableSession.>>> sess = RefreshableSession( >>> method='custom', >>> custom_credentials_method=your_custom_credential_getter, >>> custom_credentials_method_args={...}, >>> )
- get_identity() Identity[source]#
Returns metadata about the custom credential getter.
- Returns:
- Identity
Dict containing information about the custom credential getter.
- client(*args, eviction_policy: Literal['LRU', 'LFU'] | None = None, max_size: int | None = None, **kwargs) BaseClient[source]#
Returns a cached client from the default session if it exists, otherwise creates a new client and caches it.
Added in version 2.1.0.
- Parameters:
- eviction_policyEvictionPolicy, optional
The type of cache to create. Case sensitive. Options are “LRU” and “LFU”. Defaults to “LRU”.
- max_sizeint | None, optional
The maximum size of the client cache. If None, the cache size is unlimited. Beware that modifying this value after the cache has already been initialized may evict existing clients. Default is None.
- *args
Positional arguments to be passed to the default session’s client method. Check
boto3.session.Session.clientfor more details on accepted arguments.- **kwargs
Keyword arguments to be passed to the default session’s client method. Check
boto3.session.Session.clientfor more details on accepted arguments.
- Returns:
- BaseClient
A cached client if it exists, otherwise a new client that has been cached.
- Raises:
- ClientCacheError
Raised when an error occurs related to cache operations, such as using an invalid key, eviction policy, or value type.
- ClientCacheExistsError
Raised when attempting to add a client which already exists in the cache.
- ClientCacheNotFoundError
Raised when attempting to retrieve or delete a client which does not exist in the cache.
Examples
>>> from boto3_client_cache import client >>> s3_client = client("s3", region_name="us-east-1") >>> s3_client_again = client("s3", region_name="us-east-1") >>> s3_client is s3_client_again True
- property credentials: TemporaryCredentials[source]#
The current temporary AWS security credentials.
Alias for
refreshable_credentials.
- get_available_partitions()[source]#
Lists the available partitions
- Return type:
- Returns:
Returns a list of partition names (e.g., [“aws”, “aws-cn”])
- get_available_regions(service_name, partition_name='aws', allow_non_regional=False)[source]#
Lists the region and endpoint names of a particular partition.
The list of regions returned by this method are regions that are explicitly known by the client to exist and is not comprehensive. A region not returned in this list may still be available for the provided service.
- Parameters:
service_name (string) – Name of a service to list endpoint for (e.g., s3).
partition_name (string) – Name of the partition to limit endpoints to. (e.g., aws for the public AWS endpoints, aws-cn for AWS China endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc.)
allow_non_regional (bool) – Set to True to include endpoints that are not regional endpoints (e.g., s3-external-1, fips-us-gov-west-1, etc).
- Returns:
Returns a list of endpoint names (e.g., [“us-east-1”]).
- get_available_resources()[source]#
Get a list of available services that can be loaded as resource clients via
Session.resource.- Return type:
- Returns:
List of service names
- get_available_services()[source]#
Get a list of available services that can be loaded as low-level clients via
Session.client.- Return type:
- Returns:
List of service names
- get_credentials()[source]#
Return the
botocore.credentials.Credentialsobject 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.
- get_partition_for_region(region_name)[source]#
Lists the partition name of a particular region.
- Parameters:
region_name (string) – Name of the region to list partition for (e.g., us-east-1).
- Return type:
string
- Returns:
Returns the respective partition name (e.g., aws).
- refreshable_credentials() TemporaryCredentials[source]#
Returns the current temporary AWS security credentials.
- Returns:
- TemporaryCredentials
- Temporary AWS security credentials containing:
- access_keystr
AWS access key identifier.
- secret_keystr
AWS secret access key.
- tokenstr
AWS session token.
- expiry_timestr
Expiration timestamp in ISO 8601 format.
- resource(*args, eviction_policy: Literal['LRU', 'LFU'] | None = None, max_size: int | None = None, **kwargs) ServiceResource[source]#
Returns a cached resource from the default session if it exists, otherwise creates a new resource and caches it.
Added in version 2.1.0.
- Parameters:
- eviction_policyEvictionPolicy, optional
The type of cache to create. Case sensitive. Options are “LRU” and “LFU”. Defaults to “LRU”.
- max_sizeint | None, optional
The maximum size of the resource cache. If None, the cache size is unlimited. Beware that modifying this value after the cache has already been initialized may evict existing resources. Default is None.
- *args
Positional arguments to be passed to the default session’s resource method. Check
boto3.session.Session.resourcefor more details on accepted arguments.- **kwargs
Keyword arguments to be passed to the default session’s resource method. Check
boto3.session.Session.resourcefor more details on accepted arguments.
- Returns:
- ServiceResource
A cached resource if it exists, otherwise a new resource that has been cached.
- Raises:
- ResourceCacheError
Raised when an error occurs related to cache operations, such as using an invalid key, eviction policy, or value type.
- ResourceCacheExistsError
Raised when attempting to add a resource which already exists in the cache.
- ResourceCacheNotFoundError
Raised when attempting to retrieve or delete a resource which does not exist in the cache.
Notes
Tip
For correct typing, you may want to import mypy-boto3-* and use the generated type annotations for casting clients, which will be compatible with this method.
Examples
>>> from boto3_client_cache import resource >>> s3_resource = resource("s3", region_name="us-east-1") >>> s3_resource_again = resource("s3", region_name="us-east-1") >>> s3_resource is s3_resource_again True