Get a local copy of a file from django storages S3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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