Commits

Stephen McDonald committed 3869082 Merge

Merged in joshcartme/filebrowser-safe/PEP8 (pull request #5)

Numerous PEP8 style fixes and removal of unused imports.

  • Participants
  • Parent commits 0e49b43, 618b0fd

Comments (0)

Files changed (9)

File filebrowser_safe/base.py

 # coding: utf-8
 
 # imports
-import os, re, datetime, time, mimetypes
-from time import gmtime, strftime
+import os
+import datetime
+import time
+import mimetypes
 
 # django imports
-from django.conf import settings
 from django.core.files.storage import default_storage
 from django.utils.encoding import smart_str, smart_unicode
 
 # filebrowser imports
 from filebrowser_safe.settings import *
-from filebrowser_safe.functions import (get_file_type, url_join, is_selectable,
-                                        path_strip)
+from filebrowser_safe.functions import get_file_type, path_strip
 
 
 class FileObject():
         self.filename_root, self.extension = os.path.splitext(self.filename)
         self.mimetype = mimetypes.guess_type(self.filename)
 
-
     def __str__(self):
         return smart_str(self.path)
 
 
     # GENERAL ATTRIBUTES
     _filetype_stored = None
+
     def _filetype(self):
         if self._filetype_stored != None:
             return self._filetype_stored
     filetype = property(_filetype)
 
     _filesize_stored = None
+
     def _filesize(self):
         if self._filesize_stored != None:
             return self._filesize_stored
     filesize = property(_filesize)
 
     _date_stored = None
+
     def _date(self):
         if self._date_stored != None:
             return self._date_stored
     datetime = property(_datetime)
 
     _exists_stored = None
+
     def exists(self):
         if self._exists_stored == None:
             self._exists_stored = default_storage.exists(self.path)
     directory = property(_directory)
 
     def _folder(self):
-        return os.path.dirname(path_strip(os.path.join(self.head,''), DIRECTORY))
+        return os.path.dirname(path_strip(os.path.join(self.head, ''), DIRECTORY))
     folder = property(_folder)
 
     _is_folder_stored = None
+
     def _is_folder(self):
         if self._is_folder_stored == None:
             self._is_folder_stored = default_storage.isdir(self.path)
                 default_storage.delete(version)
             except:
                 pass
-
-

File filebrowser_safe/decorators.py

 # coding: utf-8
 
 # django imports
-from django.contrib.sessions.models import Session
-from django.shortcuts import get_object_or_404, render_to_response
+from django.shortcuts import get_object_or_404
 from django.contrib.auth.models import User
-from django.template import RequestContext
 from django.conf import settings
 
 
     Decorator to recognize a user  by its session.
     Used for Flash-Uploading.
     """
-    
+
     def decorator(request, *args, **kwargs):
         try:
             engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
         request.user = get_object_or_404(User, pk=user_id)
         return function(request, *args, **kwargs)
     return decorator
-
-

File filebrowser_safe/forms.py

 # coding: utf-8
 
 # imports
-import re, os
+import os
+import re
 
 # django imports
 from django import forms
-from django.forms.formsets import BaseFormSet
 from django.utils.translation import ugettext as _
 
 # filebrowser imports
-from filebrowser_safe.settings import MAX_UPLOAD_SIZE, FOLDER_REGEX
+from filebrowser_safe.settings import FOLDER_REGEX
 
 
 alnum_name_re = re.compile(FOLDER_REGEX)
 
+
 class MakeDirForm(forms.Form):
     """
     Form for creating Folder.
         self.path = path
         super(MakeDirForm, self).__init__(*args, **kwargs)
 
-    dir_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)
+    dir_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)
 
     def clean_dir_name(self):
         if self.cleaned_data['dir_name']:
             # only letters, numbers, underscores, spaces and hyphens are allowed.
             if not alnum_name_re.search(self.cleaned_data['dir_name']):
-                raise forms.ValidationError(_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'))
+                raise forms.ValidationError(
+                    _(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'))
             # Folder must not already exist.
             if os.path.isdir(os.path.join(self.path, self.cleaned_data['dir_name'])):
                 raise forms.ValidationError(_(u'The Folder already exists.'))
         self.file_extension = file_extension
         super(RenameForm, self).__init__(*args, **kwargs)
 
-    name = forms.CharField(widget=forms.TextInput(attrs=dict({ 'class': 'vTextField' }, max_length=50, min_length=3)), label=_(u'New Name'), help_text=_('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=_(u'New Name'),
+        help_text=_('Only letters, numbers, underscores, spaces and hyphens are allowed.'),
+        required=True)
 
     def clean_name(self):
         if self.cleaned_data['name']:
             elif os.path.isfile(os.path.join(self.path, self.cleaned_data['name'] + self.file_extension)):
                 raise forms.ValidationError(_(u'The File already exists.'))
         return self.cleaned_data['name']
-
-

File filebrowser_safe/functions.py

 # coding: utf-8
 
 # imports
-import os, re, decimal, unicodedata
-from time import gmtime, strftime, localtime, mktime, time
-from urlparse import urlparse
+import os
+import re
+import unicodedata
+from time import gmtime, strftime, localtime, time
 
 # django imports
-from django.utils.translation import ugettext as _
-from django.utils.safestring import mark_safe
-from django.core.files import File
 from django.core.files.storage import default_storage
 
 # filebrowser imports
     # (seq[i].attr, i, seq[i]) and sort it. The second item of tuple is needed not
     # only to provide stable sorting, but mainly to eliminate comparison of objects
     # (which can be expensive or prohibited) in case of equal attribute values.
-    intermed = map(None, map(getattr, seq, (attr,)*len(seq)), xrange(len(seq)), seq)
+    intermed = map(None, map(getattr, seq, (attr,) * len(seq)),
+                   xrange(len(seq)), seq)
     intermed.sort()
     return map(operator.getitem, intermed, (-1,) * len(intermed))
 
     dir_query = ""
     if path:
         for item in path.split(os.sep):
-            dir_query = os.path.join(dir_query,item)
-            breadcrumbs.append([item,dir_query])
+            dir_query = os.path.join(dir_query, item)
+            breadcrumbs.append([item, dir_query])
     return breadcrumbs
 
 
     dateYear = strftime("%Y", gmtime(dateTime))
     dateMonth = strftime("%m", gmtime(dateTime))
     dateDay = strftime("%d", gmtime(dateTime))
-    if filterDate == 'today' and int(dateYear) == int(localtime()[0]) and int(dateMonth) == int(localtime()[1]) and int(dateDay) == int(localtime()[2]): returnvalue = 'true'
-    elif filterDate == 'thismonth' and dateTime >= time()-2592000: returnvalue = 'true'
-    elif filterDate == 'thisyear' and int(dateYear) == int(localtime()[0]): returnvalue = 'true'
-    elif filterDate == 'past7days' and dateTime >= time()-604800: returnvalue = 'true'
-    elif filterDate == '': returnvalue = 'true'
+    if filterDate == ('today' and
+                       int(dateYear) == int(localtime()[0]) and
+                       int(dateMonth) == int(localtime()[1]) and
+                       int(dateDay) == int(localtime()[2])):
+        returnvalue = 'true'
+    elif filterDate == 'thismonth' and dateTime >= time() - 2592000:
+        returnvalue = 'true'
+    elif filterDate == 'thisyear' and int(dateYear) == int(localtime()[0]):
+        returnvalue = 'true'
+    elif filterDate == 'past7days' and dateTime >= time() - 604800:
+        returnvalue = 'true'
+    elif filterDate == '':
+        returnvalue = 'true'
     return returnvalue
 
 
 
     file_extension = os.path.splitext(filename)[1].lower()
     file_type = ''
-    for k,v in EXTENSIONS.iteritems():
+    for k, v in EXTENSIONS.iteritems():
         for extension in v:
             if file_extension == extension.lower():
                 file_type = k
 
     file_extension = os.path.splitext(filename)[1].lower()
     select_types = []
-    for k,v in SELECT_FORMATS.iteritems():
+    for k, v in SELECT_FORMATS.iteritems():
         for extension in v:
             if file_extension == extension.lower():
                 select_types.append(k)

File filebrowser_safe/settings.py

 # Therefore, if you add a category (e.g. "Misc"), you won't get an icon.
 EXTENSIONS = getattr(settings, "FILEBROWSER_EXTENSIONS", {
     'Folder': [''],
-    'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff'],
-    'Video': ['.mov','.wmv','.mpeg','.mpg','.avi','.rm'],
-    'Document': ['.pdf','.doc','.rtf','.txt','.xls','.csv'],
-    'Audio': ['.mp3','.mp4','.wav','.aiff','.midi','.m4p'],
-    'Code': ['.html','.py','.js','.css']
+    'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'],
+    'Video': ['.mov', '.wmv', '.mpeg', '.mpg', '.avi', '.rm'],
+    'Document': ['.pdf', '.doc', '.rtf', '.txt', '.xls', '.csv'],
+    'Audio': ['.mp3', '.mp4', '.wav', '.aiff', '.midi', '.m4p'],
+    'Code': ['.html', '.py', '.js', '.css']
 })
 
 # Define different formats for allowed selections.
 # This has to be a subset of EXTENSIONS.
 SELECT_FORMATS = getattr(settings, "FILEBROWSER_SELECT_FORMATS", {
-    'File': ['Folder','Document',],
+    'File': ['Folder', 'Document'],
     'Image': ['Image'],
-    'Media': ['Video','Audio'],
+    'Media': ['Video', 'Audio'],
     'Document': ['Document'],
     # for TinyMCE we can also define lower-case items
     'image': ['Image'],
-    'file': ['Folder','Image','Document',],
-    'media': ['Video','Audio'],
+    'file': ['Folder', 'Image', 'Document'],
+    'media': ['Video', 'Audio'],
 })
 
 # Directory to Save Image Versions (and Thumbnails). Relative to MEDIA_ROOT.
 #     'croppedthumbnail': {'verbose_name': 'Cropped Thumbnail (140x140px)', 'width': 140, 'height': 140, 'opts': 'crop'},
 # })
 # Versions available within the Admin-Interface.
-ADMIN_VERSIONS = getattr(settings, 'FILEBROWSER_ADMIN_VERSIONS', ['thumbnail','small', 'medium','big'])
+ADMIN_VERSIONS = getattr(settings,
+                         'FILEBROWSER_ADMIN_VERSIONS',
+                         ['thumbnail', 'small', 'medium', 'big'])
 # Which Version should be used as Admin-thumbnail.
 ADMIN_THUMBNAIL = getattr(settings, 'FILEBROWSER_ADMIN_THUMBNAIL', 'fb_thumb')
 
 STRICT_PIL = getattr(settings, 'FILEBROWSER_STRICT_PIL', False)
 # PIL's Error "Suspension not allowed here" work around:
 # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html
-IMAGE_MAXBLOCK = getattr(settings, 'FILEBROWSER_IMAGE_MAXBLOCK', 1024*1024)
+IMAGE_MAXBLOCK = getattr(settings, 'FILEBROWSER_IMAGE_MAXBLOCK', 1024 * 1024)
 # Exclude files matching any of the following regular expressions
 # Default is to exclude 'thumbnail' style naming of image-thumbnails.
 EXTENSION_LIST = []
 _('Document')
 _('Audio')
 _('Code')
-
-

File filebrowser_safe/storage.py

 # coding: utf-8
 
 # PYTHON IMPORTS
-import os, shutil
+import os
+import shutil
 
 # DJANGO IMPORTS
 from django.core.files.move import file_move_safe
 from django.core.files.base import ContentFile
 
+
 class StorageMixin(object):
     """
     Adds some useful methods to the Storage class.
     def rmtree(self, name):
         shutil.rmtree(self.path(name))
 
+
 class S3BotoStorageMixin(StorageMixin):
 
     def isfile(self, name):
         # That's some inefficient implementation...
         # If there are some files having 'name' as their prefix, then
         # the name is considered to be a directory
-        if not name: # Empty name is a directory
+        if not name:  # Empty name is a directory
             return True
 
         if self.isfile(name):
         for item in dirlist:
             item.delete()
 
+
 class GoogleStorageMixin(StorageMixin):
 
     def isfile(self, name):
         # That's some inefficient implementation...
         # If there are some files having 'name' as their prefix, then
         # the name is considered to be a directory
-        if not name: # Empty name is a directory
+        if not name:  # Empty name is a directory
             return True
 
         if self.isfile(name):

File filebrowser_safe/templatetags/fb_pagination.py

 # coding: utf-8
 
-from django.utils.html import escape
-from django.utils.safestring import mark_safe
 from django.template import Library
 
 register = Library()
 
 DOT = '.'
 
+
 @register.inclusion_tag('filebrowser/include/paginator.html', takes_context=True)
 def pagination(context):
-    page_num = context['page'].number-1
+    page_num = context['page'].number - 1
     paginator = context['p']
-    
+
     if not paginator.num_pages or paginator.num_pages == 1:
         page_range = []
     else:
         ON_EACH_SIDE = 3
         ON_ENDS = 2
-        
+
         # If there are 10 or fewer pages, display links to every page.
         # Otherwise, do some fancy
         if paginator.num_pages <= 10:
                 page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
             else:
                 page_range.extend(range(page_num + 1, paginator.num_pages))
-    
+
     return {
         'page_range': page_range,
         'page_num': page_num,
         'results_var': context['results_var'],
         'query': context['query'],
     }
-
-

File filebrowser_safe/templatetags/fb_tags.py

 
 # django imports
 from django import template
-from django.utils.encoding import smart_unicode
 from django.utils.safestring import mark_safe
 
 # filebrowser imports
     remove = string_to_list(remove)
     params = context['query'].copy()
     response = get_query_string(params, add, remove)
-    return {'response': response }
+    return {'response': response}
 
 
 def query_helper(query, add=None, remove=None):
     Add and remove query parameters. From `django.contrib.admin`.
     """
 
-    if new_params is None: new_params = {}
-    if remove is None: remove = []
+    if new_params is None:
+        new_params = {}
+    if remove is None:
+        remove = []
     for r in remove:
         for k in p.keys():
             #if k.startswith(r):
             string += ','
         for arg in string.split(','):
             arg = arg.strip()
-            if arg == '': continue
+            if arg == '':
+                continue
             kw, val = arg.split('=', 1)
             kwargs[kw] = val
     return kwargs
             string += ','
         for arg in string.split(','):
             arg = arg.strip()
-            if arg == '': continue
+            if arg == '':
+                continue
             args.append(arg)
     return args
 

File filebrowser_safe/views.py

 # coding: utf-8
 
 # general imports
-import os, re
-from time import gmtime, strftime
+import os
+import re
 
 # django imports
 from django.conf import settings as django_settings
 
 # filebrowser imports
 from filebrowser_safe.settings import *
-from filebrowser_safe.functions import (path_to_url, sort_by_attr, get_path,
-                get_file, get_breadcrumbs, get_filterdate, get_settings_var,
+from filebrowser_safe.functions import (sort_by_attr, get_path,
+                get_breadcrumbs, get_filterdate, get_settings_var,
                 convert_filename)
 from filebrowser_safe.templatetags.fb_tags import query_helper
 from filebrowser_safe.base import FileObject
 from filebrowser_safe.decorators import flash_login_required
-from filebrowser_safe.storage import FileSystemStorageMixin
 
 from mezzanine.utils.importing import import_dotted_path
 
 # Precompile regular expressions
 filter_re = []
 for exp in EXCLUDE:
-   filter_re.append(re.compile(exp))
-for k,v in VERSIONS.iteritems():
+    filter_re.append(re.compile(exp))
+for k, v in VERSIONS.iteritems():
     exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST))
     filter_re.append(re.compile(exp))
 
     abs_path = os.path.join(DIRECTORY, path)
 
     # INITIAL VARIABLES
-    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 }
+    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0}
     counter = {}
-    for k,v in EXTENSIONS.iteritems():
+    for k, v in EXTENSIONS.iteritems():
         counter[k] = 0
 
     dir_list, file_list = default_storage.listdir(abs_path)
 filebrowser_pre_createdir = Signal(providing_args=["path", "dirname"])
 filebrowser_post_createdir = Signal(providing_args=["path", "dirname"])
 
+
 def mkdir(request):
     """
     Make Directory.
     }, context_instance=Context(request))
 upload = staff_member_required(never_cache(upload))
 
+
 @csrf_exempt
 def _check_file(request):
     """
     folder = fb_uploadurl_re.sub('', folder)
     fileArray = {}
     if request.method == 'POST':
-        for k,v in request.POST.items():
+        for k, v in request.POST.items():
             if k != "folder":
                 if default_storage.exists(os.path.join(DIRECTORY, folder, v)):
                     fileArray[k] = v
 filebrowser_pre_upload = Signal(providing_args=["path", "file"])
 filebrowser_post_upload = Signal(providing_args=["path", "file"])
 
+
 @csrf_exempt
 @flash_login_required
 @staff_member_required
 filebrowser_pre_delete = Signal(providing_args=["path", "filename"])
 filebrowser_post_delete = Signal(providing_args=["path", "filename"])
 
+
 def delete(request):
     """
     Delete existing File/Directory.
 filebrowser_pre_rename = Signal(providing_args=["path", "filename", "new_filename"])
 filebrowser_post_rename = Signal(providing_args=["path", "filename", "new_filename"])
 
+
 def rename(request):
     """
     Rename existing File/Directory.