

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Python 搭配用戶端快取取得 Secrets Manager 秘密值
<a name="retrieving-secrets_cache-python"></a>

擷取秘密時，您可以使用 Secrets Manager Python 型快取元件進行快取以供將來使用。擷取快取的秘密比從 Secrets Manager 中擷取要快。由於呼叫 Secrets Manager API 需要花費成本，因此使用快取可以降低成本。如需您可以擷取機密的所有方法，請參閱 [取得秘密](retrieving-secrets.md)。

快取政策是「最近最少使用的 (LRU)」，因此當快取必須丟棄秘密時，其會丟棄最近最少使用的秘密。預設情況下，快取每小時重新整理一次秘密。您可以設定在快取中[重新整理機密的頻率](retrieving-secrets_cache-ref-secretcacheconfig.md)，並可以[掛接到機密擷取](retrieving-secrets_cache-ref-secretcachehook.md)以新增更多功能。

一旦釋放快取參考，快取不會強制執行垃圾回收。快取實作不包括快取失效。快取實作著重於快取本身，而不是強化或著重於安全性。如果您需要額外的安全性，例如加密快取中的項目，請使用提供的介面和抽象方法。

若要使用元件，您必須擁有下列項目：
+ Python 3.6 或更高版本。
+ botocore 1.12 或更高版本。請參閱 [AWS SDK for Python](https://aws.amazon.com/sdk-for-python/) 和 [Botocore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html)。
+ setuptools\_scm 3.2 或更高版本。請參閱 [https://pypi.org/project/setuptools-scm/](https://pypi.org/project/setuptools-scm/)。

若要下載開放程式碼，請參閱 [Secrets Manager Python 型快取用戶端元件](https://github.com/aws/aws-secretsmanager-caching-python ) (在 GitHub 上)。

若要安裝元件，請使用下列命令。

```
$ pip install aws-secretsmanager-caching
```

**必要許可：**
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

如需詳細資訊，請參閱[許可參考](auth-and-access.md#reference_iam-permissions)。

**Topics**
+ [SecretCache](retrieving-secrets_cache-ref-secretcache.md)
+ [SecretCacheConfig](retrieving-secrets_cache-ref-secretcacheconfig.md)
+ [SecretCacheHook](retrieving-secrets_cache-ref-secretcachehook.md)
+ [@InjectSecretString](retrieving-secrets_cache-decor-string.md)
+ [@InjectKeywordedSecretString](retrieving-secrets_cache-decor-keyword.md)

**Example 擷取秘密**  
以下範例顯示如何為名為 {{mysecret}} 的秘密取得秘密值。  

```
import botocore 
import botocore.session 
from aws_secretsmanager_caching import SecretCache, SecretCacheConfig 

client = botocore.session.get_session().create_client('secretsmanager')
cache_config = SecretCacheConfig()
cache = SecretCache( config = cache_config, client = client)

secret = cache.get_secret_string('{{mysecret}}')
```