From e268efa5e78c71554717fcde3a6aa64f894516c3 Mon Sep 17 00:00:00 2001 From: Stephen Mitchell Date: Fri, 5 Jul 2024 21:31:10 -0400 Subject: [PATCH] [s3] Cache Cloudfront Signers (#1417) --- CHANGELOG.rst | 2 ++ storages/backends/s3.py | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 0b0085fb..2a2045ec 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,6 +10,7 @@ S3 - Pull ``AWS_SESSION_TOKEN`` from the environment (`#1399`_) - Fix newline handling for text mode files (`#1381`_) - Do not sign URLs when ``querystring_auth=False`` e.g public buckets or static files (`#1402`_) +- Cache CloudFront Signers (`#1417`_) Azure ----- @@ -22,6 +23,7 @@ Azure .. _#1402: https://github.com/jschneier/django-storages/pull/1402 .. _#1403: https://github.com/jschneier/django-storages/pull/1403 .. _#1414: https://github.com/jschneier/django-storages/pull/1414 +.. _#1417: https://github.com/jschneier/django-storages/pull/1417 1.14.3 (2024-05-04) diff --git a/storages/backends/s3.py b/storages/backends/s3.py index 3230f305..dbeb97e0 100644 --- a/storages/backends/s3.py +++ b/storages/backends/s3.py @@ -311,6 +311,8 @@ class S3Storage(CompressStorageMixin, BaseStorage): # settings/args are ignored. config = None + _signers = {} # noqa: RUF012 + def __init__(self, **settings): omitted = object() if not hasattr(self, "cloudfront_signer"): @@ -372,7 +374,12 @@ def __init__(self, **settings): self.cloudfront_signer = None def get_cloudfront_signer(self, key_id, key): - return _cloud_front_signer_from_pem(key_id, key) + cache_key = f"{key_id}:{key}" + if cache_key not in self.__class__._signers: + self.__class__._signers[cache_key] = _cloud_front_signer_from_pem( + key_id, key + ) + return self.__class__._signers[cache_key] def get_default_settings(self): return {