Skip to content

Instantly share code, notes, and snippets.

@ark4n631
Last active April 23, 2024 19:48
Show Gist options
  • Save ark4n631/641f6bad1fa9c766643b98d7a9099529 to your computer and use it in GitHub Desktop.
Save ark4n631/641f6bad1fa9c766643b98d7a9099529 to your computer and use it in GitHub Desktop.
Get a local copy of a file from django storages S3
from django.core.files import File
from django.core.files.storage import default_storage, FileSystemStorage
from django.conf import settings
from django.core.files.base import ContentFile
local_storage = FileSystemStorage()
local_storage.base_location = settings.MEDIA_ROOT
def get_local_file_from_object(obj):
"""
obj.binary = FileField()
"""
if default_storage.__class__ == 'your.settings.backend.cloud.Class':
# If we are using cloud storage we have to retrieve the file locally if doesn't exists...
filename = 'tmp/'+obj.binary.name
# If the file is not on local storage download it...
if not local_storage.exists(filename):
local_storage.save(filename, ContentFile(obj.binary.read()))
# if exist retrieve the abs path
local_file_path = local_storage.path(filename)
else:
# If storage is not cloud retrieve the path from the local storage
local_file_path = obj.binary.path
return File(open(local_file_path, 'rb'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment