Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add string format and os.path.join #48

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 65 additions & 79 deletions filemanager/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,22 +61,22 @@ def __init__(

def rename_if_exists(self, folder, file):
if folder[-1] != os.sep:
folder = folder + os.sep
if os.path.exists(folder + file):
folder = '{}{}'.format(folder, os.sep)
if os.path.exists('{}{}'.format(folder, file)):
if file.find('.') == -1:
# no extension
for i in range(1000):
if not os.path.exists(folder + file + '.' + str(i)):
if not os.path.exists('{}{}.{}'.format(folder, file, str(i))):
break
return file + '.' + str(i)
return '{}.{}'.format(file, str(i))
else:
extension = file[file.rfind('.'):]
name = file[:file.rfind('.')]
for i in range(1000):
full_path = folder + name + '.' + str(i) + extension
full_path = '{}{}.{}{}'.format(folder, name, str(i), extension)
if not os.path.exists(full_path):
break
return name + '.' + str(i) + extension
return '{}.{}{}'.format(name, str(i), extension)
else:
return file

Expand Down Expand Up @@ -106,7 +106,7 @@ def handle_form(self, form, files):
and not re.match(r'[\w\d_ -]+', name).group(0) == name
)
if invalid_folder_name:
messages.append("Invalid folder name : " + name)
messages.append("Invalid folder name : {}".format(name))
return messages

invalid_file_name = (
Expand All @@ -118,12 +118,12 @@ def handle_form(self, form, files):
)
)
if invalid_file_name:
messages.append("Invalid file name : " + name)
messages.append("Invalid file name : {}".format(name))
return messages

invalid_path = not re.match(r'[\w\d_ -/]+', path).group(0) == path
if invalid_path:
messages.append("Invalid path : " + path)
messages.append("Invalid path : {}".format(path))
return messages
if action == 'upload':
for f in files.getlist('ufile'):
Expand All @@ -132,13 +132,10 @@ def handle_form(self, form, files):
or not re.match('[\w\d_ -/.]+', f.name).group(0) == f.name
)
if file_name_invalid:
messages.append("File name is not valid : " + f.name)
messages.append("File name is not valid : {}".format(f.name))
elif f.size > self.maxfilesize*1024:
messages.append(
"File size exceeded "
+ str(self.maxfilesize)
+ " KB : "
+ f.name
"File size exceeded {} KB : {}".format(str(self.maxfilesize), f.name)
)
elif (
settings.FILEMANAGER_CHECK_SPACE and
Expand All @@ -148,21 +145,15 @@ def handle_form(self, form, files):
)
):
messages.append(
"Total Space size exceeded "
+ str(self.maxspace)
+ " KB : "
+ f.name
"Total Space size exceeded {} KB : {}".format(str(self.maxspace), f.name)
)
elif (
self.extensions
and len(f.name.split('.')) > 1
and f.name.split('.')[-1] not in self.extensions
):
messages.append(
"File extension not allowed (."
+ f.name.split('.')[-1]
+ ") : "
+ f.name
"File extension not allowed (.{}) : {}".format(f.name.split('.')[-1], f.name)
)
elif (
self.extensions
Expand All @@ -171,15 +162,16 @@ def handle_form(self, form, files):
not in self.extensions
):
messages.append(
"No file extension in uploaded file : "
+ f.name
"No file extension in uploaded file : {}".format(f.name)
)
else:
filename = f.name.replace(' ', '_') # replace spaces to prevent fs error
path_with_bath = '{}{}'.format(self.basepath, path)
filepath = (
self.basepath
+ path
+ self.rename_if_exists(self.basepath + path, filename)
'{}{}'.format(
path_with_bath,
self.rename_if_exists(path_with_bath, filename)
)
)
with open(filepath, 'w') as dest:
for chunk in f.chunks():
Expand All @@ -192,49 +184,48 @@ def handle_form(self, form, files):
no_of_folders = len(list(os.walk('.')))
if (no_of_folders + 1) <= self.maxfolders:
try:
os.chdir(self.basepath + path)
os.chdir('{}{}'.format(self.basepath, path))
os.mkdir(name)
messages.append('Folder created successfully : ' + name)
messages.append('Folder created successfully : {}'.format(name))
except OSError:
messages.append('Folder couldn\'t be created : ' + name)
messages.append('Folder couldn\'t be created : {}'.format(name))
except Exception as e:
messages.append('Unexpected error : ' + e)
messages.append('Unexpected error : {}'.format(e))
else:
messages.append(
'Folder couldn\' be created because maximum number of '
+ 'folders exceeded : '
+ str(self.maxfolders)
'{}{}{}'.format(
'Folder couldn\' be created ',
'because maximum number of folders exceeded : ',
str(self.maxfolders),
)
)
elif action == 'rename' and file_or_dir == 'dir':
oldname = path.split('/')[-2]
path = '/'.join(path.split('/')[:-2])
try:
os.chdir(self.basepath + path)
os.chdir('{}{}'.format(self.basepath, path))
os.rename(oldname, name)
messages.append(
'Folder renamed successfully from '
+ oldname
+ ' to '
+ name
'Folder renamed successfully from {} to {}'.format(oldname, name)
)
except OSError:
messages.append('Folder couldn\'t renamed to ' + name)
messages.append('Folder couldn\'t renamed to {}'.format(name))
except Exception as e:
messages.append('Unexpected error : ' + e)
messages.append('Unexpected error : {}'.format(e))
elif action == 'delete' and file_or_dir == 'dir':
if path == '/':
messages.append('root folder can\'t be deleted')
else:
name = path.split('/')[-2]
path = '/'.join(path.split('/')[:-2])
try:
os.chdir(self.basepath + path)
os.chdir('{}{}'.format(self.basepath, path))
shutil.rmtree(name)
messages.append('Folder deleted successfully : ' + name)
messages.append('Folder deleted successfully : {}'.format(name))
except OSError:
messages.append('Folder couldn\'t deleted : ' + name)
messages.append('Folder couldn\'t deleted : {}'.format(name))
except Exception as e:
messages.append('Unexpected error : ' + e)
messages.append('Unexpected error : {}'.format(e))
elif action == 'rename' and file_or_dir == 'file':
oldname = path.split('/')[-1]
old_ext = (
Expand All @@ -246,28 +237,23 @@ def handle_form(self, form, files):
if old_ext == new_ext:
path = '/'.join(path.split('/')[:-1])
try:
os.chdir(self.basepath + path)
os.chdir('{}{}'.format(self.basepath, path))
os.rename(oldname, name)
messages.append(
'File renamed successfully from '
+ oldname
+ ' to '
+ name
'File renamed successfully from {} to {}'.format(oldname, name)
)
except OSError:
messages.append('File couldn\'t be renamed to ' + name)
messages.append('File couldn\'t be renamed to {}'.format(name))
except Exception as e:
messages.append('Unexpected error : ' + e)
messages.append('Unexpected error : {}'.format(e))
else:
if old_ext:
messages.append(
'File extension should be same : .'
+ old_ext
'File extension should be same : .{}'.format(old_ext)
)
else:
messages.append(
'New file extension didn\'t match with old file'
+ ' extension'
'New file extension didn\'t match with old file extension'
)
elif action == 'delete' and file_or_dir == 'file':
if path == '/':
Expand All @@ -276,28 +262,32 @@ def handle_form(self, form, files):
name = path.split('/')[-1]
path = '/'.join(path.split('/')[:-1])
try:
os.chdir(self.basepath + path)
os.chdir('{}{}'.format(self.basepath, path))
os.remove(name)
messages.append('File deleted successfully : ' + name)
messages.append('File deleted successfully : {}'.format(name))
except OSError:
messages.append('File couldn\'t deleted : ' + name)
messages.append('File couldn\'t deleted : {}'.format(name))
except Exception as e:
messages.append('Unexpected error : ' + e)
messages.append('Unexpected error : {}'.format(e))
elif action == 'move' or action == 'copy':
# from path to current_path
if self.current_path.find(path) == 0:
messages.append('Cannot move/copy to a child folder')
else:
path = os.path.normpath(path) # strip trailing slash if any
filename = (
self.basepath
+ self.current_path
+ os.path.basename(path)
'{}{}{}'.format(
self.basepath,
self.current_path,
os.path.basename(path)
)
)
if os.path.exists(filename):
messages.append(
'ERROR: A file/folder with this name already exists in'
+ ' the destination folder.'
'{}{}'.format(
'ERROR: A file/folder with this name already ',
'exists in the destination folder.'
)
)
else:
if action == 'move':
Expand All @@ -308,13 +298,13 @@ def handle_form(self, form, files):
else:
method = shutil.copy
try:
method(self.basepath + path, filename)
method('{}{}'.format(self.basepath, path), filename)
except OSError:
messages.append(
'File/folder couldn\'t be moved/copied.'
)
except Exception as e:
messages.append('Unexpected error : ' + e)
messages.append('Unexpected error : {}'.format(e))
return messages

def directory_structure(self):
Expand All @@ -335,7 +325,7 @@ def directory_structure(self):
for d in directory_list:
current_dir = nextdirs[d]
nextdirs = current_dir['dirs']
if directory[1:] + '/' == self.current_path:
if '{}{}'.format(directory[1:], '/') == self.current_path:
self.current_id = current_dir['id']
current_dir['dirs'].update(
dict(
Expand All @@ -361,15 +351,15 @@ def media(self, path):
try:
mimetypes.init()
mimetype = mimetypes.guess_type(path)[0]
img = Image.open(self.basepath + '/' + path)
img = Image.open('{}/{}'.format(self.basepath, path))
width, height = img.size
mx = max([width, height])
w, h = width, height
if mx > 60:
w = width*60/mx
h = height*60/mx
img = img.resize((w, h), Image.ANTIALIAS)
response = HttpResponse(content_type=mimetype or "image/" + ext)
response = HttpResponse(content_type=mimetype or "image/{}".format(ext))
response['Cache-Control'] = 'max-age=3600'
img.save(
response,
Expand All @@ -378,15 +368,11 @@ def media(self, path):
return response
except Exception:
imagepath = (
settings.FILEMANAGER_STATIC_ROOT
+ 'images/icons/'
+ ext
+ '.png'
'{}images/icons/{}.png'.format(settings.FILEMANAGER_STATIC_ROOT, ext)
)
if not os.path.exists(imagepath):
imagepath = (
settings.FILEMANAGER_STATIC_ROOT
+ 'images/icons/default.png'
'{}images/icons/default.png'.format(settings.FILEMANAGER_STATIC_ROOT)
)
img = Image.open(imagepath)
width, height = img.size
Expand All @@ -405,19 +391,19 @@ def download(self, path, file_or_dir):
if not re.match(r'[\w\d_ -/]*', path).group(0) == path:
return HttpResponse('Invalid path')
if file_or_dir == 'file':
filepath = self.basepath + '/' + path
filepath = '{}/{}'.format(self.basepath, path)
wrapper = FileWrapper(open(filepath))
response = HttpResponse(
wrapper,
content_type=mimetypes.guess_type(filepath)[0],
)
response['Content-Length'] = os.path.getsize(filepath)
response['Content-Disposition'] = (
'attachment; filename=' + path.split('/')[-1]
'attachment; filename={}'.format(path.split('/')[-1])
)
return response
elif file_or_dir == 'dir':
dirpath = self.basepath + '/' + path
dirpath = '{}/{}'.format(self.basepath, path)
dirname = dirpath.split('/')[-2]
response = HttpResponse(content_type='application/x-gzip')
response['Content-Disposition'] = (
Expand Down
2 changes: 1 addition & 1 deletion filemanager/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
FILEMANAGER_STATIC_ROOT = getattr(
settings,
'FILEMANAGER_STATIC_ROOT',
os.path.dirname(os.path.abspath(__file__)) + '/static/filemanager/',
os.path.dirname(os.path.join(os.path.abspath(__file__), 'static', 'filemanager')),
)
FILEMANAGER_CKEDITOR_JS = getattr(
settings,
Expand Down