Skip to content

Commit

Permalink
Merge pull request #421 from claudep/remove_python2_leftovers
Browse files Browse the repository at this point in the history
Removed old syntax used to ensure Python 2 compatibility
  • Loading branch information
sehmaschine authored Oct 14, 2024
2 parents db343bb + 592ca75 commit f8875e9
Show file tree
Hide file tree
Showing 30 changed files with 96 additions and 171 deletions.
14 changes: 6 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
#
# Django FileBrowser documentation build configuration file, created by
# sphinx-quickstart on Sun Dec 5 19:11:46 2010.
#
Expand Down Expand Up @@ -43,8 +41,8 @@
master_doc = 'index'

# General information about the project.
project = u'Django FileBrowser'
copyright = u'2022, Patrick Kranzlmueller'
project = 'Django FileBrowser'
copyright = '2022, Patrick Kranzlmueller'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -182,8 +180,8 @@
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'DjangoFileBrowser.tex', u'Django FileBrowser Documentation',
u'Patrick Kranzlmueller', 'manual'),
('index', 'DjangoFileBrowser.tex', 'Django FileBrowser Documentation',
'Patrick Kranzlmueller', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -215,8 +213,8 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'djangofilebrowser', u'Django FileBrowser Documentation',
[u'Patrick Kranzlmueller'], 1)
('index', 'djangofilebrowser', 'Django FileBrowser Documentation',
['Patrick Kranzlmueller'], 1)
]

if not on_rtd: # only import and set the theme if we're building docs locally
Expand Down
2 changes: 1 addition & 1 deletion docs/fieldswidgets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ Return a :ref:`fileobject` from a `FileField <https://docs.djangoproject.com/en/
from filebrowser.base import FileObject
image_upload = models.ImageField(u"Image (Upload)", max_length=250, upload_to=image_upload_path, blank=True)
image_upload = models.ImageField("Image (Upload)", max_length=250, upload_to=image_upload_path, blank=True)
def image(self):
if self.image_upload:
Expand Down
12 changes: 5 additions & 7 deletions filebrowser/actions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

import os
import tempfile

Expand Down Expand Up @@ -52,33 +50,33 @@ def transpose_image(request, fileobjects, operation):
def flip_horizontal(request, fileobjects):
"Flip image horizontally"
transpose_image(request, fileobjects, 0)
flip_horizontal.short_description = _(u'Flip horizontal')
flip_horizontal.short_description = _('Flip horizontal')
flip_horizontal.applies_to = applies_to_all_images


def flip_vertical(request, fileobjects):
"Flip image vertically"
transpose_image(request, fileobjects, 1)
flip_vertical.short_description = _(u'Flip vertical')
flip_vertical.short_description = _('Flip vertical')
flip_vertical.applies_to = applies_to_all_images


def rotate_90_clockwise(request, fileobjects):
"Rotate image 90 degrees clockwise"
transpose_image(request, fileobjects, 4)
rotate_90_clockwise.short_description = _(u'Rotate 90° CW')
rotate_90_clockwise.short_description = _('Rotate 90° CW')
rotate_90_clockwise.applies_to = applies_to_all_images


def rotate_90_counterclockwise(request, fileobjects):
"Rotate image 90 degrees counterclockwise"
transpose_image(request, fileobjects, 2)
rotate_90_counterclockwise.short_description = _(u'Rotate 90° CCW')
rotate_90_counterclockwise.short_description = _('Rotate 90° CCW')
rotate_90_counterclockwise.applies_to = applies_to_all_images


def rotate_180(request, fileobjects):
"Rotate image 180 degrees"
transpose_image(request, fileobjects, 3)
rotate_180.short_description = _(u'Rotate 180°')
rotate_180.short_description = _('Rotate 180°')
rotate_180.applies_to = applies_to_all_images
7 changes: 1 addition & 6 deletions filebrowser/base.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
# coding: utf-8

import datetime
import mimetypes
import os
import platform
import tempfile
import time

from six import python_2_unicode_compatible, string_types

from django.core.files import File
from django.utils.encoding import force_str
from django.utils.functional import cached_property
Expand Down Expand Up @@ -82,7 +78,7 @@ def sort_by_attr(self, seq, attr):
the sorted list of objects.
"""
from operator import attrgetter
if isinstance(attr, string_types): # Backward compatibility hack
if isinstance(attr, str): # Backward compatibility hack
attr = (attr, )
return sorted(seq, key=attrgetter(*attr))

Expand Down Expand Up @@ -200,7 +196,6 @@ def results_walk_filtered(self):
return len(self.files_walk_filtered())


@python_2_unicode_compatible
class FileObject():
"""
The FileObject represents a file (or directory) on the server.
Expand Down
11 changes: 4 additions & 7 deletions filebrowser/decorators.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
# coding: utf-8

import os

from django.contrib import messages
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _

from filebrowser.templatetags.fb_tags import query_helper


def get_path(path, site):
converted_path = smart_str(os.path.join(site.directory, path))
converted_path = os.path.join(site.directory, path)
if not path.startswith('.') and not os.path.isabs(converted_path):
if site.storage.isdir(converted_path):
return path


def get_file(path, filename, site):
# Files and directories are valid
converted_path = smart_str(os.path.join(site.directory, path, filename))
converted_path = os.path.join(site.directory, path, filename)
if not path.startswith('.') and not filename.startswith('.') and not os.path.isabs(converted_path):
if site.storage.isfile(converted_path) or site.storage.isdir(converted_path):
return filename
Expand All @@ -38,7 +35,7 @@ def decorator(request, *args, **kwargs):
if get_path(request.GET.get('dir', ''), site=site) is None:
msg = _('The requested Folder does not exist.')
messages.add_message(request, messages.ERROR, msg)
redirect_url = reverse("filebrowser:fb_browse", current_app=site.name) + query_helper(request.GET, u"", "dir")
redirect_url = reverse("filebrowser:fb_browse", current_app=site.name) + query_helper(request.GET, "", "dir")
return HttpResponseRedirect(redirect_url)
return function(request, *args, **kwargs)
return decorator
Expand All @@ -52,7 +49,7 @@ def decorator(request, *args, **kwargs):
if file_path is None:
msg = _('The requested File does not exist.')
messages.add_message(request, messages.ERROR, msg)
redirect_url = reverse("filebrowser:fb_browse", current_app=site.name) + query_helper(request.GET, u"", "dir")
redirect_url = reverse("filebrowser:fb_browse", current_app=site.name) + query_helper(request.GET, "", "dir")
return HttpResponseRedirect(redirect_url)
return function(request, *args, **kwargs)
return decorator
5 changes: 2 additions & 3 deletions filebrowser/fields.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
import os

from django import forms
Expand Down Expand Up @@ -57,7 +56,7 @@ def render(self, name, value, attrs=None, renderer=None):
class FileBrowseFormField(forms.CharField):

default_error_messages = {
'extension': _(u'Extension %(ext)s is not allowed. Only %(allowed)s is allowed.'),
'extension': _('Extension %(ext)s is not allowed. Only %(allowed)s is allowed.'),
}

def __init__(self, max_length=None, min_length=None, site=None, directory=None, extensions=None, format=None, *args, **kwargs):
Expand Down Expand Up @@ -180,7 +179,7 @@ def render(self, name, value, attrs=None, renderer=None):
class FileBrowseUploadFormField(forms.CharField):

default_error_messages = {
'extension': _(u'Extension %(ext)s is not allowed. Only %(allowed)s is allowed.'),
'extension': _('Extension %(ext)s is not allowed. Only %(allowed)s is allowed.'),
}

def __init__(self, max_length=None, min_length=None, site=None, directory=None, extensions=None, format=None, upload_to=None, temp_upload_dir=None, *args, **kwargs):
Expand Down
32 changes: 15 additions & 17 deletions filebrowser/forms.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

import os
import re

Expand All @@ -13,12 +11,12 @@
ALNUM_NAME_RE = re.compile(FOLDER_REGEX, re.U)

TRANSPOSE_CHOICES = (
("", u"-----"),
("0", _(u"Flip horizontal")),
("1", _(u"Flip vertical")),
("2", _(u"Rotate 90° CW")),
("4", _(u"Rotate 90° CCW")),
("3", _(u"Rotate 180°")),
("", "-----"),
("0", _("Flip horizontal")),
("1", _("Flip vertical")),
("2", _("Rotate 90° CW")),
("4", _("Rotate 90° CCW")),
("3", _("Rotate 180°")),
)


Expand All @@ -27,7 +25,7 @@ class CreateDirForm(forms.Form):
Form for creating a folder.
"""

name = forms.CharField(widget=forms.TextInput(attrs=dict({'class': 'vTextField'}, max_length=50, min_length=3)), label=_(u'Name'), help_text=_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True)
name = forms.CharField(widget=forms.TextInput(attrs=dict({'class': 'vTextField'}, max_length=50, min_length=3)), label=_('Name'), help_text=_('Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True)

def __init__(self, path, *args, **kwargs):
self.path = path
Expand All @@ -39,10 +37,10 @@ def clean_name(self):
if self.cleaned_data['name']:
# only letters, numbers, underscores, spaces and hyphens are allowed.
if not ALNUM_NAME_RE.search(self.cleaned_data['name']):
raise forms.ValidationError(_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'))
raise forms.ValidationError(_('Only letters, numbers, underscores, spaces and hyphens are allowed.'))
# Folder must not already exist.
if self.site.storage.isdir(os.path.join(self.path, convert_filename(self.cleaned_data['name']))):
raise forms.ValidationError(_(u'The Folder already exists.'))
raise forms.ValidationError(_('The Folder already exists.'))
return convert_filename(self.cleaned_data['name'])


Expand All @@ -51,8 +49,8 @@ class ChangeForm(forms.Form):
Form for renaming a file/folder.
"""

custom_action = forms.ChoiceField(label=_(u'Actions'), required=False)
name = forms.CharField(widget=forms.TextInput(attrs=dict({'class': 'vTextField'}, max_length=50, min_length=3)), label=_(u'Name'), help_text=_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True)
custom_action = forms.ChoiceField(label=_('Actions'), required=False)
name = forms.CharField(widget=forms.TextInput(attrs=dict({'class': 'vTextField'}, max_length=50, min_length=3)), label=_('Name'), help_text=_('Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True)

def __init__(self, *args, **kwargs):
self.path = kwargs.pop("path", None)
Expand All @@ -61,7 +59,7 @@ def __init__(self, *args, **kwargs):
super(ChangeForm, self).__init__(*args, **kwargs)

# Initialize choices of custom action
choices = [("", u"-----")]
choices = [("", "-----")]
for name, action in self.site.applicable_actions(self.fileobject):
choices.append((name, action.short_description))
self.fields['custom_action'].choices = choices
Expand All @@ -71,10 +69,10 @@ def clean_name(self):
if self.cleaned_data['name']:
# only letters, numbers, underscores, spaces and hyphens are allowed.
if not ALNUM_NAME_RE.search(self.cleaned_data['name']):
raise forms.ValidationError(_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'))
raise forms.ValidationError(_('Only letters, numbers, underscores, spaces and hyphens are allowed.'))
# folder/file must not already exist.
if self.site.storage.isdir(os.path.join(self.path, convert_filename(self.cleaned_data['name']))) and os.path.join(self.path, convert_filename(self.cleaned_data['name'])) != self.fileobject.path:
raise forms.ValidationError(_(u'The Folder already exists.'))
raise forms.ValidationError(_('The Folder already exists.'))
elif self.site.storage.isfile(os.path.join(self.path, convert_filename(self.cleaned_data['name']))) and os.path.join(self.path, convert_filename(self.cleaned_data['name'])) != self.fileobject.path:
raise forms.ValidationError(_(u'The File already exists.'))
raise forms.ValidationError(_('The File already exists.'))
return convert_filename(self.cleaned_data['name'])
4 changes: 0 additions & 4 deletions filebrowser/management/commands/fb_version_generate.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
# coding: utf-8

import os
import re

from six.moves import input

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from filebrowser.base import FileListing
Expand Down
3 changes: 0 additions & 3 deletions filebrowser/management/commands/fb_version_remove.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
# coding: utf-8
import os
import re
import sys

from six.moves import input

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from filebrowser.settings import EXCLUDE, EXTENSIONS
Expand Down
12 changes: 4 additions & 8 deletions filebrowser/namers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
from __future__ import unicode_literals

import re

import six

from django.utils.encoding import force_str
from django.utils.module_loading import import_string

Expand All @@ -15,7 +11,7 @@ def get_namer(**kwargs):
return namer_cls(**kwargs)


class VersionNamer(object):
class VersionNamer:
"Base namer only for reference"

def __init__(self, **kwargs):
Expand Down Expand Up @@ -88,11 +84,11 @@ def options_list(self):
if v is True:
opts.append(k)
continue
if not isinstance(v, six.string_types):
if not isinstance(v, str):
try:
v = 'x'.join([six.text_type(v) for item in v])
v = 'x'.join([str(v) for item in v])
except TypeError:
v = six.text_type(v)
v = str(v)
opts.append('%s-%s' % (k, v))

return opts
2 changes: 0 additions & 2 deletions filebrowser/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

from django.conf import settings
from django.utils.translation import gettext_lazy as _

Expand Down
2 changes: 0 additions & 2 deletions filebrowser/signals.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

from django.dispatch import Signal

# upload signals
Expand Down
Loading

0 comments on commit f8875e9

Please sign in to comment.