2008-08-09 04:59:02 +08:00
|
|
|
import os
|
2008-08-28 05:44:14 +08:00
|
|
|
import errno
|
2012-07-20 21:36:52 +08:00
|
|
|
try:
|
|
|
|
from urllib.parse import urljoin
|
|
|
|
except ImportError: # Python 2
|
|
|
|
from urlparse import urljoin
|
2010-02-24 06:39:22 +08:00
|
|
|
import itertools
|
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
|
2013-02-03 05:58:02 +08:00
|
|
|
from django.core.exceptions import SuspiciousOperation
|
2009-03-02 12:48:47 +08:00
|
|
|
from django.core.files import locks, File
|
|
|
|
from django.core.files.move import file_move_safe
|
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
|
2013-02-03 05:58:02 +08:00
|
|
|
from django.utils.module_loading import import_by_path
|
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
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
__all__ = ('Storage', 'FileSystemStorage', 'DefaultStorage', 'default_storage')
|
|
|
|
|
|
|
|
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):
|
|
|
|
"""
|
|
|
|
Saves new content to the file specified by name. The content should be a
|
|
|
|
proper File object, ready to be read from the beginning.
|
|
|
|
"""
|
|
|
|
# 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
|
|
|
|
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)
|
2010-02-24 06:39:22 +08:00
|
|
|
# If the filename already exists, add an underscore and a number (before
|
|
|
|
# the file extension, if one exists) to the filename until the generated
|
2009-05-08 13:50:31 +08:00
|
|
|
# filename doesn't exist.
|
2010-02-24 06:39:22 +08:00
|
|
|
count = itertools.count(1)
|
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.
|
2012-05-11 02:14:04 +08:00
|
|
|
name = os.path.join(dir_name, "%s_%s%s" % (file_root, next(count), 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.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def exists(self, name):
|
|
|
|
"""
|
|
|
|
Returns True if a file referened by the given name already exists in the
|
|
|
|
storage system, or False if the name is available for a new file.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def size(self, name):
|
|
|
|
"""
|
|
|
|
Returns the total size, in bytes, of the file specified by name.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
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
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def created_time(self, name):
|
|
|
|
"""
|
|
|
|
Returns the creation time (as datetime object) of the file
|
|
|
|
specified by name.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def modified_time(self, name):
|
|
|
|
"""
|
|
|
|
Returns the last modified time (as datetime object) of the file
|
|
|
|
specified by name.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
class FileSystemStorage(Storage):
|
|
|
|
"""
|
|
|
|
Standard filesystem storage
|
|
|
|
"""
|
|
|
|
|
2009-03-02 12:48:47 +08:00
|
|
|
def __init__(self, location=None, base_url=None):
|
|
|
|
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
|
2008-08-09 04:59:02 +08:00
|
|
|
self.base_url = base_url
|
|
|
|
|
|
|
|
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:
|
|
|
|
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)
|
|
|
|
content.close()
|
|
|
|
|
|
|
|
# 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)
|
2008-08-12 00:51:18 +08:00
|
|
|
try:
|
|
|
|
locks.lock(fd, locks.LOCK_EX)
|
2012-08-29 21:13:20 +08:00
|
|
|
_file = None
|
2008-08-12 00:51:18 +08:00
|
|
|
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
|
|
|
|
2008-08-28 06:21:14 +08:00
|
|
|
if settings.FILE_UPLOAD_PERMISSIONS is not None:
|
|
|
|
os.chmod(full_path, settings.FILE_UPLOAD_PERMISSIONS)
|
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):
|
|
|
|
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):
|
|
|
|
try:
|
|
|
|
path = safe_join(self.location, name)
|
|
|
|
except ValueError:
|
|
|
|
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
|
2010-03-03 05:58:49 +08:00
|
|
|
return os.path.normpath(path)
|
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)))
|
|
|
|
|
2009-03-02 12:48:47 +08:00
|
|
|
def get_storage_class(import_path=None):
|
2013-02-03 05:58:02 +08:00
|
|
|
return import_by_path(import_path or settings.DEFAULT_FILE_STORAGE)
|
2008-08-09 04:59:02 +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()
|