Created
July 26, 2012 16:24
-
-
Save bryanchow/3183057 to your computer and use it in GitHub Desktop.
Django uploaded filename utility functions
This file contains hidden or 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
# Django uploaded filename utility functions | |
# https://gist.github.com/3183057 | |
import os, itertools | |
from django.core.exceptions import SuspiciousOperation | |
from django.utils._os import safe_join, abspathu | |
from django.utils.text import get_valid_filename | |
from django.conf import settings | |
def path(name, location): | |
""" | |
Return a validated path. | |
Adapted from django.core.files.storage.FileSystemStorage | |
""" | |
location = abspathu(location) | |
try: | |
path = safe_join(location, name) | |
except ValueError: | |
raise SuspiciousOperation("Attempted access to '%s' denied." % name) | |
return os.path.normpath(path) | |
def get_available_name(name, location=None): | |
""" | |
Return a filename that is not present on the filesystem. | |
Adapted from django.core.files.storage.Storage | |
""" | |
if location is None: | |
location = settings.MEDIA_ROOT | |
dir_name, file_name = os.path.split(name) | |
file_root, file_ext = os.path.splitext(file_name) | |
# If the filename already exists, add an underscore and a number (before | |
# the file extension, if one exists) to the filename until the generated | |
# filename doesn't exist. | |
count = itertools.count(1) | |
while os.path.exists(path(name, location)): | |
# file_ext includes the dot. | |
name = os.path.join(dir_name, "%s_%s%s" % (file_root, count.next(), file_ext)) | |
return name | |
def get_available_valid_name(name, location=None): | |
""" | |
Return a cleaned filename that is not present on the filesystem. | |
""" | |
return get_available_name(get_valid_filename(name), location) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment