-
-
Notifications
You must be signed in to change notification settings - Fork 45
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: auto-remove temporary files
- Loading branch information
Showing
3 changed files
with
71 additions
and
75 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,30 @@ | ||
import contextlib | ||
import os | ||
import tempfile | ||
from typing import Generator | ||
|
||
from django.core.files import File | ||
|
||
def get_fieldfile_local_path(fieldfile): | ||
local_temp_file = None | ||
|
||
if hasattr(fieldfile, 'storage'): | ||
@contextlib.contextmanager | ||
def get_local_path(fieldfile: File) -> Generator[str, None, None]: | ||
if not hasattr(fieldfile, 'storage'): | ||
# Its a local file with no storage abstraction | ||
try: | ||
yield os.path.abspath(fieldfile.path) | ||
except AttributeError: | ||
yield os.path.abspath(fieldfile.name) | ||
else: | ||
storage = fieldfile.storage | ||
try: | ||
# Try to access with path | ||
storage_local_path = storage.path(fieldfile.path) | ||
yield storage.path(fieldfile.path) | ||
except (NotImplementedError, AttributeError): | ||
# Storage doesnt support absolute paths, download | ||
# file to a temp local dir | ||
storage_file = storage.open(fieldfile.name, 'rb') | ||
|
||
local_temp_file = tempfile.NamedTemporaryFile(delete=False) | ||
local_temp_file.write(storage_file.read()) | ||
local_temp_file.close() | ||
storage_local_path = local_temp_file.name | ||
else: | ||
# Its a local file with no storage abstraction | ||
try: | ||
path = os.path.abspath(fieldfile.path) | ||
except AttributeError: | ||
path = os.path.abspath(fieldfile.name) | ||
|
||
storage_local_path = path | ||
# Storage doesnt support absolute paths, | ||
# download file to a temp local dir | ||
with tempfile.NamedTemporaryFile(delete=False) as temp_file: | ||
storage_file = storage.open(fieldfile.name, 'r') | ||
|
||
return storage_local_path, local_temp_file | ||
temp_file.write(storage_file.read()) | ||
temp_file.flush() | ||
yield temp_file.name |