2008-08-09 04:59:02 +08:00
|
|
|
import os
|
2008-08-28 05:44:14 +08:00
|
|
|
import errno
|
2010-10-08 23:11:59 +08:00
|
|
|
from datetime import datetime
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
2009-03-02 12:48:47 +08:00
|
|
|
from django.core.files import locks, File
|
|
|
|
from django.core.files.move import file_move_safe
|
2014-08-08 22:20:08 +08:00
|
|
|
from django.utils.crypto import get_random_string
|
2012-07-21 16:00:10 +08:00
|
|
|
from django.utils.encoding import force_text, filepath_to_uri
|
2009-03-02 12:48:47 +08:00
|
|
|
from django.utils.functional import LazyObject
|
2014-01-21 04:15:14 +08:00
|
|
|
from django.utils.module_loading import import_string
|
2013-09-06 03:38:59 +08:00
|
|
|
from django.utils.six.moves.urllib.parse import urljoin
|
2008-08-09 23:16:47 +08:00
|
|
|
from django.utils.text import get_valid_filename
|
2011-09-21 23:58:32 +08:00
|
|
|
from django.utils._os import safe_join, abspathu
|
2014-05-07 13:23:23 +08:00
|
|
|
from django.utils.deconstruct import deconstructible
|
2011-09-21 23:58:32 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
__all__ = ('Storage', 'FileSystemStorage', 'DefaultStorage', 'default_storage')
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
class Storage(object):
|
|
|
|
"""
|
|
|
|
A base storage class, providing some default behaviors that all other
|
|
|
|
storage systems can inherit or override, as necessary.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# The following methods represent a public interface to private methods.
|
|
|
|
# These shouldn't be overridden by subclasses unless absolutely necessary.
|
|
|
|
|
2011-09-13 23:10:49 +08:00
|
|
|
def open(self, name, mode='rb'):
|
2008-08-09 04:59:02 +08:00
|
|
|
"""
|
2011-09-13 23:10:49 +08:00
|
|
|
Retrieves the specified file from storage.
|
2008-08-09 04:59:02 +08:00
|
|
|
"""
|
2011-09-13 23:10:49 +08:00
|
|
|
return self._open(name, mode)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def save(self, name, content):
|
|
|
|
"""
|
2013-02-23 20:42:04 +08:00
|
|
|
Saves new content to the file specified by name. The content should be
|
|
|
|
a proper File object or any python file-like object, ready to be read
|
|
|
|
from the beginning.
|
2008-08-09 04:59:02 +08:00
|
|
|
"""
|
|
|
|
# Get the proper name for the file, as it will actually be saved.
|
|
|
|
if name is None:
|
|
|
|
name = content.name
|
2009-03-02 12:48:47 +08:00
|
|
|
|
2013-02-23 20:42:04 +08:00
|
|
|
if not hasattr(content, 'chunks'):
|
|
|
|
content = File(content)
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
name = self.get_available_name(name)
|
2008-08-12 00:51:18 +08:00
|
|
|
name = self._save(name, content)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
# Store filenames with forward slashes, even on Windows
|
2012-07-21 16:00:10 +08:00
|
|
|
return force_text(name.replace('\\', '/'))
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
# These methods are part of the public API, with default implementations.
|
|
|
|
|
|
|
|
def get_valid_name(self, name):
|
|
|
|
"""
|
|
|
|
Returns a filename, based on the provided filename, that's suitable for
|
|
|
|
use in the target storage system.
|
|
|
|
"""
|
|
|
|
return get_valid_filename(name)
|
|
|
|
|
|
|
|
def get_available_name(self, name):
|
|
|
|
"""
|
|
|
|
Returns a filename that's free on the target storage system, and
|
|
|
|
available for new content to be written to.
|
|
|
|
"""
|
2009-05-08 13:50:31 +08:00
|
|
|
dir_name, file_name = os.path.split(name)
|
|
|
|
file_root, file_ext = os.path.splitext(file_name)
|
2014-08-08 22:20:08 +08:00
|
|
|
# If the filename already exists, add an underscore and a random 7
|
|
|
|
# character alphanumeric string (before the file extension, if one
|
|
|
|
# exists) to the filename until the generated filename doesn't exist.
|
2008-08-09 04:59:02 +08:00
|
|
|
while self.exists(name):
|
2009-05-08 13:50:31 +08:00
|
|
|
# file_ext includes the dot.
|
2014-08-08 22:20:08 +08:00
|
|
|
name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext))
|
2010-02-24 06:39:22 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
return name
|
|
|
|
|
|
|
|
def path(self, name):
|
|
|
|
"""
|
|
|
|
Returns a local filesystem path where the file can be retrieved using
|
|
|
|
Python's built-in open() function. Storage systems that can't be
|
|
|
|
accessed using open() should *not* implement this method.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError("This backend doesn't support absolute paths.")
|
|
|
|
|
|
|
|
# The following methods form the public API for storage systems, but with
|
|
|
|
# no default implementations. Subclasses must implement *all* of these.
|
|
|
|
|
|
|
|
def delete(self, name):
|
|
|
|
"""
|
|
|
|
Deletes the specified file from the storage system.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide a delete() method')
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def exists(self, name):
|
|
|
|
"""
|
2014-01-21 00:33:11 +08:00
|
|
|
Returns True if a file referenced by the given name already exists in the
|
2008-08-09 04:59:02 +08:00
|
|
|
storage system, or False if the name is available for a new file.
|
|
|
|
"""
|
2014-05-29 08:39:14 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide an exists() method')
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def listdir(self, path):
|
|
|
|
"""
|
|
|
|
Lists the contents of the specified path, returning a 2-tuple of lists;
|
|
|
|
the first item being directories, the second item being files.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide a listdir() method')
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def size(self, name):
|
|
|
|
"""
|
|
|
|
Returns the total size, in bytes, of the file specified by name.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide a size() method')
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def url(self, name):
|
|
|
|
"""
|
|
|
|
Returns an absolute URL where the file's contents can be accessed
|
2010-10-09 16:12:50 +08:00
|
|
|
directly by a Web browser.
|
2008-08-09 04:59:02 +08:00
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide a url() method')
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2010-10-08 23:11:59 +08:00
|
|
|
def accessed_time(self, name):
|
|
|
|
"""
|
|
|
|
Returns the last accessed time (as datetime object) of the file
|
|
|
|
specified by name.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide an accessed_time() method')
|
2010-10-08 23:11:59 +08:00
|
|
|
|
|
|
|
def created_time(self, name):
|
|
|
|
"""
|
|
|
|
Returns the creation time (as datetime object) of the file
|
|
|
|
specified by name.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide a created_time() method')
|
2010-10-08 23:11:59 +08:00
|
|
|
|
|
|
|
def modified_time(self, name):
|
|
|
|
"""
|
|
|
|
Returns the last modified time (as datetime object) of the file
|
|
|
|
specified by name.
|
|
|
|
"""
|
2013-09-07 02:24:52 +08:00
|
|
|
raise NotImplementedError('subclasses of Storage must provide a modified_time() method')
|
2010-10-08 23:11:59 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2014-05-07 13:23:23 +08:00
|
|
|
@deconstructible
|
2008-08-09 04:59:02 +08:00
|
|
|
class FileSystemStorage(Storage):
|
|
|
|
"""
|
|
|
|
Standard filesystem storage
|
|
|
|
"""
|
|
|
|
|
2013-11-05 18:02:54 +08:00
|
|
|
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
|
2014-11-23 05:30:14 +08:00
|
|
|
directory_permissions_mode=None, **kwargs):
|
2009-03-02 12:48:47 +08:00
|
|
|
if location is None:
|
|
|
|
location = settings.MEDIA_ROOT
|
2011-09-21 23:58:32 +08:00
|
|
|
self.base_location = location
|
|
|
|
self.location = abspathu(self.base_location)
|
2009-03-02 12:48:47 +08:00
|
|
|
if base_url is None:
|
|
|
|
base_url = settings.MEDIA_URL
|
2014-05-29 01:03:26 +08:00
|
|
|
elif not base_url.endswith('/'):
|
|
|
|
base_url += '/'
|
2008-08-09 04:59:02 +08:00
|
|
|
self.base_url = base_url
|
2013-10-19 20:40:12 +08:00
|
|
|
self.file_permissions_mode = (
|
|
|
|
file_permissions_mode if file_permissions_mode is not None
|
|
|
|
else settings.FILE_UPLOAD_PERMISSIONS
|
|
|
|
)
|
2013-11-05 18:02:54 +08:00
|
|
|
self.directory_permissions_mode = (
|
|
|
|
directory_permissions_mode if directory_permissions_mode is not None
|
|
|
|
else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS
|
|
|
|
)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def _open(self, name, mode='rb'):
|
|
|
|
return File(open(self.path(name), mode))
|
|
|
|
|
|
|
|
def _save(self, name, content):
|
|
|
|
full_path = self.path(name)
|
|
|
|
|
2011-05-26 16:21:35 +08:00
|
|
|
# Create any intermediate directories that do not exist.
|
|
|
|
# Note that there is a race between os.path.exists and os.makedirs:
|
|
|
|
# if os.makedirs fails with EEXIST, the directory was created
|
|
|
|
# concurrently, and we can continue normally. Refs #16082.
|
2008-08-09 04:59:02 +08:00
|
|
|
directory = os.path.dirname(full_path)
|
|
|
|
if not os.path.exists(directory):
|
2011-05-26 16:21:35 +08:00
|
|
|
try:
|
2013-11-05 18:02:54 +08:00
|
|
|
if self.directory_permissions_mode is not None:
|
2013-05-13 19:38:53 +08:00
|
|
|
# os.makedirs applies the global umask, so we reset it,
|
2013-11-05 18:02:54 +08:00
|
|
|
# for consistency with file_permissions_mode behavior.
|
2013-05-13 19:38:53 +08:00
|
|
|
old_umask = os.umask(0)
|
|
|
|
try:
|
2013-11-05 18:02:54 +08:00
|
|
|
os.makedirs(directory, self.directory_permissions_mode)
|
2013-05-13 19:38:53 +08:00
|
|
|
finally:
|
|
|
|
os.umask(old_umask)
|
|
|
|
else:
|
|
|
|
os.makedirs(directory)
|
2012-04-29 00:09:37 +08:00
|
|
|
except OSError as e:
|
2011-05-26 16:21:35 +08:00
|
|
|
if e.errno != errno.EEXIST:
|
|
|
|
raise
|
|
|
|
if not os.path.isdir(directory):
|
2008-08-09 04:59:02 +08:00
|
|
|
raise IOError("%s exists and is not a directory." % directory)
|
2008-08-12 00:51:18 +08:00
|
|
|
|
|
|
|
# There's a potential race condition between get_available_name and
|
|
|
|
# saving the file; it's possible that two threads might return the
|
|
|
|
# same name, at which point all sorts of fun happens. So we need to
|
|
|
|
# try to create the file, but if it already exists we have to go back
|
|
|
|
# to get_available_name() and try again.
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
# This file has a file path that we can move.
|
|
|
|
if hasattr(content, 'temporary_file_path'):
|
|
|
|
file_move_safe(content.temporary_file_path(), full_path)
|
|
|
|
|
|
|
|
# This is a normal uploadedfile that we can stream.
|
|
|
|
else:
|
|
|
|
# This fun binary flag incantation makes os.open throw an
|
|
|
|
# OSError if the file already exists before we open it.
|
2012-09-05 23:05:28 +08:00
|
|
|
flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL |
|
|
|
|
getattr(os, 'O_BINARY', 0))
|
|
|
|
# The current umask value is masked out by os.open!
|
|
|
|
fd = os.open(full_path, flags, 0o666)
|
2013-05-18 00:29:41 +08:00
|
|
|
_file = None
|
2008-08-12 00:51:18 +08:00
|
|
|
try:
|
|
|
|
locks.lock(fd, locks.LOCK_EX)
|
|
|
|
for chunk in content.chunks():
|
2012-08-29 21:13:20 +08:00
|
|
|
if _file is None:
|
|
|
|
mode = 'wb' if isinstance(chunk, bytes) else 'wt'
|
|
|
|
_file = os.fdopen(fd, mode)
|
|
|
|
_file.write(chunk)
|
2008-08-12 00:51:18 +08:00
|
|
|
finally:
|
|
|
|
locks.unlock(fd)
|
2012-08-29 21:13:20 +08:00
|
|
|
if _file is not None:
|
|
|
|
_file.close()
|
|
|
|
else:
|
|
|
|
os.close(fd)
|
2012-04-29 00:09:37 +08:00
|
|
|
except OSError as e:
|
2008-08-28 05:44:14 +08:00
|
|
|
if e.errno == errno.EEXIST:
|
|
|
|
# Ooops, the file exists. We need a new file name.
|
|
|
|
name = self.get_available_name(name)
|
|
|
|
full_path = self.path(name)
|
|
|
|
else:
|
|
|
|
raise
|
2008-08-12 00:51:18 +08:00
|
|
|
else:
|
|
|
|
# OK, the file save worked. Break out of the loop.
|
|
|
|
break
|
2009-03-02 12:48:47 +08:00
|
|
|
|
2013-10-19 20:40:12 +08:00
|
|
|
if self.file_permissions_mode is not None:
|
|
|
|
os.chmod(full_path, self.file_permissions_mode)
|
2009-03-02 12:48:47 +08:00
|
|
|
|
2008-08-12 00:51:18 +08:00
|
|
|
return name
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def delete(self, name):
|
2013-06-27 16:59:30 +08:00
|
|
|
assert name, "The name argument is not allowed to be empty."
|
2008-08-09 04:59:02 +08:00
|
|
|
name = self.path(name)
|
|
|
|
# If the file exists, delete it from the filesystem.
|
2011-05-28 21:06:08 +08:00
|
|
|
# Note that there is a race between os.path.exists and os.remove:
|
|
|
|
# if os.remove fails with ENOENT, the file was removed
|
|
|
|
# concurrently, and we can continue normally.
|
2008-08-09 04:59:02 +08:00
|
|
|
if os.path.exists(name):
|
2011-05-28 21:06:08 +08:00
|
|
|
try:
|
|
|
|
os.remove(name)
|
2012-04-29 00:09:37 +08:00
|
|
|
except OSError as e:
|
2011-05-28 21:06:08 +08:00
|
|
|
if e.errno != errno.ENOENT:
|
|
|
|
raise
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def exists(self, name):
|
|
|
|
return os.path.exists(self.path(name))
|
|
|
|
|
|
|
|
def listdir(self, path):
|
|
|
|
path = self.path(path)
|
|
|
|
directories, files = [], []
|
|
|
|
for entry in os.listdir(path):
|
|
|
|
if os.path.isdir(os.path.join(path, entry)):
|
|
|
|
directories.append(entry)
|
|
|
|
else:
|
|
|
|
files.append(entry)
|
|
|
|
return directories, files
|
|
|
|
|
|
|
|
def path(self, name):
|
2014-11-12 01:59:49 +08:00
|
|
|
return safe_join(self.location, name)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def size(self, name):
|
|
|
|
return os.path.getsize(self.path(name))
|
|
|
|
|
|
|
|
def url(self, name):
|
|
|
|
if self.base_url is None:
|
|
|
|
raise ValueError("This file is not accessible via a URL.")
|
2012-07-20 21:36:52 +08:00
|
|
|
return urljoin(self.base_url, filepath_to_uri(name))
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2010-10-08 23:11:59 +08:00
|
|
|
def accessed_time(self, name):
|
|
|
|
return datetime.fromtimestamp(os.path.getatime(self.path(name)))
|
|
|
|
|
|
|
|
def created_time(self, name):
|
|
|
|
return datetime.fromtimestamp(os.path.getctime(self.path(name)))
|
|
|
|
|
|
|
|
def modified_time(self, name):
|
|
|
|
return datetime.fromtimestamp(os.path.getmtime(self.path(name)))
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-03-02 12:48:47 +08:00
|
|
|
def get_storage_class(import_path=None):
|
2014-01-21 04:15:14 +08:00
|
|
|
return import_string(import_path or settings.DEFAULT_FILE_STORAGE)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-03-02 12:48:47 +08:00
|
|
|
class DefaultStorage(LazyObject):
|
|
|
|
def _setup(self):
|
|
|
|
self._wrapped = get_storage_class()()
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
default_storage = DefaultStorage()
|