Skip to content

Instantly share code, notes, and snippets.

@ark4n631
Last active May 10, 2023 15:59
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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