Description
Imagine I want to store a file in different AWS regions based on customer country. If customer A is from Brazil, then I'd like to store it in sa-east-1
, but if customer B is from Australia I'd like to store in ap-southeast-2
.
I see in the docs that we AWS_S3_REGION_NAME
, but that's a global configuration and not something I can change dynamically within my code.
The obvious train of though would be to extend the default storages.backends.s3.S3Storage
backend class and do the magic there. From the code, I can see that the setting is being used here. And by looking at the parent class, it seems, from here, that we are basically setting a region_name
attribute on the object.
Now, with this property, we are using it here and here to build a connection, which is being used in a couple of operations (exists, listdir, url and everything that interacts with bucket; such as _save, delete, size and get_modified_time). That leads me to the conclusion that an Storage
should be tight up with a region and the solution should be made in django's FileField
class.
Dummy code below:
class DynamicStorageFileField(models.FileField):
@staticmethod
def storage_class(country):
"""Return storage class dynamically"""
def pre_save(self, model_instance, add):
self.storage = self.get_storage_class(modal_instance.country)
model_instance.file.storage = self.storage
return super().pre_save(model_instance, add)
Is this how you'd recommend so solve this dynamic region thing? I mean, should we do it within django's context or is this something we can handle within django-storages
?
Thanks in advance!