Skip to content

Instantly share code, notes, and snippets.

@barseghyanartur
Forked from ark4n631/script.py
Created May 30, 2022 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barseghyanartur/e475814d493ba69aedfb3dd08ca82b47 to your computer and use it in GitHub Desktop.
Save barseghyanartur/e475814d493ba69aedfb3dd08ca82b47 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