Commits

Chris Beaven  committed c9b5d82

Make the code PEP8 compliant.

  • Participants
  • Parent commits fb209b0

Comments (0)

Files changed (12)

File sorl/thumbnail/base.py

             except IOError, detail:
                 raise ThumbnailException(detail)
         return self._data
+
     def _set_data(self, im):
         self._data = im
     data = property(_get_data, _set_data)

File sorl/thumbnail/main.py

 
 class DjangoThumbnail(Thumbnail):
     imagemagick_file_types = get_thumbnail_setting('IMAGEMAGICK_FILE_TYPES')
-    
+
     def __init__(self, relative_source, requested_size, opts=None,
                  quality=None, basedir=None, subdir=None, prefix=None,
                  relative_dest=None, processors=None, extension=None):
         filelike = not isinstance(relative_dest, basestring)
         if filelike:
             self.dest = relative_dest
-        else: 
+        else:
             self.dest = self._absolute_path(relative_dest)
 
         # Call generate now that the dest attribute has been set

File sorl/thumbnail/models.py

-# Needs a models.py file so that tests are picked up.
+# Needs a models.py file so that tests are picked up.

File sorl/thumbnail/processors.py

     for name in names:
         # Use rfind rather than rsplit for Python 2.3 compatibility.
         lastdot = name.rfind('.')
-        modname, attrname = name[:lastdot], name[lastdot+1:]
+        modname, attrname = name[:lastdot], name[lastdot + 1:]
         mod = __import__(modname, {}, {}, [''])
         imported.append(getattr(mod, attrname))
     return imported
 
 
 def scale_and_crop(im, requested_size, opts):
-    x, y   = [float(v) for v in im.size]
+    x, y = [float(v) for v in im.size]
     xr, yr = [float(v) for v in requested_size]
 
     if 'crop' in opts or 'max' in opts:
-        r = max(xr/x, yr/y)
+        r = max(xr / x, yr / y)
     else:
-        r = min(xr/x, yr/y)
+        r = min(xr / x, yr / y)
 
     if r < 1.0 or (r > 1.0 and 'upscale' in opts):
-        im = im.resize((int(x*r), int(y*r)), resample=Image.ANTIALIAS)
+        im = im.resize((int(x * r), int(y * r)), resample=Image.ANTIALIAS)
 
     if 'crop' in opts:
-        x, y   = [float(v) for v in im.size]
-        ex, ey = (x-min(x, xr))/2, (y-min(y, yr))/2
+        x, y = [float(v) for v in im.size]
+        ex, ey = (x - min(x, xr)) / 2, (y - min(y, yr)) / 2
         if ex or ey:
-            im = im.crop((int(ex), int(ey), int(x-ex), int(y-ey)))
+            im = im.crop((int(ex), int(ey), int(x - ex), int(y - ey)))
     return im
 scale_and_crop.valid_options = ('crop', 'upscale', 'max')
 

File sorl/thumbnail/templatetags/thumbnail.py

 import re
 import math
-from django.template import Library, Node, Variable, VariableDoesNotExist, TemplateSyntaxError
+from django.template import Library, Node, Variable, VariableDoesNotExist, \
+    TemplateSyntaxError
 from django.conf import settings
 from django.utils.encoding import force_unicode
 from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
 filesize_formats = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
 filesize_long_formats = {
     'k': 'kilo', 'M': 'mega', 'G': 'giga', 'T': 'tera', 'P': 'peta',
-    'E': 'exa', 'Z': 'zetta', 'Y': 'yotta'
+    'E': 'exa', 'Z': 'zetta', 'Y': 'yotta',
 }
 
 try:
     else:
         PROCESSORS = []
         VALID_OPTIONS = []
-TAG_SETTINGS = ['quality'] 
+TAG_SETTINGS = ['quality']
+
 
 class ThumbnailNode(Node):
     def __init__(self, source_var, size_var, opts=None,
 
     # Get the source image path and requested size.
     source_var = parser.compile_filter(args[1])
-    # Since we changed to allow filters we have to make an exception for our syntax
+    # If the size argument was a correct static format, wrap it in quotes so
+    # that it is compiled correctly.
     m = size_pat.match(args[2])
     if m:
         args[2] = '"%s"' % args[2]
             raise TemplateSyntaxError("'%s' tag received a bad argument: "
                                       "'%s'" % (tag, arg))
     return ThumbnailNode(source_var, size_var, opts=opts,
-            context_name=context_name, **kwargs)
+                         context_name=context_name, **kwargs)
 
 
 def filesize(bytes, format='auto1024'):
         else:
             base = 1024
         logarithm = bytes and math.log(bytes, base) or 0
-        index = min(int(logarithm)-1, len(filesize_formats)-1)
+        index = min(int(logarithm) - 1, len(filesize_formats) - 1)
         if index >= 0:
             if base == 1000:
-                bytes = bytes and bytes / math.pow(1000, index+1)
+                bytes = bytes and bytes / math.pow(1000, index + 1)
             else:
-                bytes = bytes >> (10*(index))
+                bytes = bytes >> (10 * (index))
                 bytes = bytes and bytes / 1024.0
             unit = filesize_formats[index]
         else:
             unit = filesize_long_formats.get(unit, '')
             if base == 1024 and unit:
                 unit = '%sbi' % unit[:2]
-            unit = '%sbyte%s' % (unit, bytes!='1' and 's' or '')
+            unit = '%sbyte%s' % (unit, bytes != '1' and 's' or '')
         else:
             unit = '%s%s' % (base == 1024 and unit.upper() or unit,
                              base == 1024 and 'iB' or 'B')
     base = filesize_formats.index(format[0]) + 1
     # Exact multiple of 1000
     if format_len == 2:
-        return bytes / (1000.0**base)
+        return bytes / (1000.0 ** base)
     # Exact multiple of 1024
     elif format_len == 3:
-        bytes = bytes >> (10*(base-1))
+        bytes = bytes >> (10 * (base - 1))
         return bytes / 1024.0
 
 

File sorl/thumbnail/tests/__init__.py

 # Unit tests:
 from sorl.thumbnail.tests.classes import ThumbnailTest, DjangoThumbnailTest
 from sorl.thumbnail.tests.templatetags import ThumbnailTagTest
-from sorl.thumbnail.tests.fields import FieldTest, ImageWithThumbnailsFieldTest, ThumbnailFieldTest
+from sorl.thumbnail.tests.fields import FieldTest, \
+    ImageWithThumbnailsFieldTest, ThumbnailFieldTest
 # Doc tests:
 from sorl.thumbnail.tests.utils import utils_tests
 from sorl.thumbnail.tests.templatetags import filesize_tests
 __test__ = {
     'utils_tests': utils_tests,
     'filesize_tests': filesize_tests,
-}
+}

File sorl/thumbnail/tests/base.py

 except NameError:
     from sets import Set as set     # For Python 2.3
 
+
 def get_default_settings():
     from sorl.thumbnail import defaults
     def_settings = {}
 PIC_SIZE = (800, 600)
 
 
-
 class ChangeSettings:
     def __init__(self):
         self.default_settings = DEFAULT_THUMBNAIL_SETTINGS.copy()
                 pass
         # Change settings back to original
         self.change_settings.revert()
-

File sorl/thumbnail/tests/classes.py

 from sorl.thumbnail.base import Thumbnail
 from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
 from sorl.thumbnail.processors import dynamic_import, get_valid_options
-from sorl.thumbnail.tests.base import BaseTest, RELATIVE_PIC_NAME, PIC_NAME, THUMB_NAME, PIC_SIZE
+from sorl.thumbnail.tests.base import BaseTest, RELATIVE_PIC_NAME, PIC_NAME,\
+    THUMB_NAME, PIC_SIZE
 
 
 class ThumbnailTest(BaseTest):

File sorl/thumbnail/tests/fields.py

 from sorl.thumbnail.tests.base import BaseTest, RELATIVE_PIC_NAME, PIC_NAME
 
 thumbnail = {
-    'size': (50, 50)
+    'size': (50, 50),
 }
 extra_thumbnails = {
     'admin': {
 extension_thumbnail = thumbnail.copy()
 extension_thumbnail['extension'] = 'png'
 
+
 # Temporary models for field_tests
 class TestThumbnailFieldModel(models.Model):
     avatar = ThumbnailField(upload_to='test', size=(300, 300))

File sorl/thumbnail/tests/templatetags.py

             'width:{{ thumb.width }}, url:{{ thumb }}')
         self.assertEqual(output, 'width:240, url:%s' % expected_url)
 
-filesize_tests = """
+filesize_tests = r"""
 >>> from sorl.thumbnail.templatetags.thumbnail import filesize
 
 >>> filesize('abc')
 1024 yobibytes, 1000 yottabytes
 
 # Test all fixed outputs (eg 'kB' or 'MiB')
->>> from sorl.thumbnail.templatetags.thumbnail import filesize_formats, filesize_long_formats
+>>> from sorl.thumbnail.templatetags.thumbnail import filesize_formats,\
+...    filesize_long_formats
 >>> for f in filesize_formats:
 ...     print '%s (%siB, %sB):' % (filesize_long_formats[f], f.upper(), f)
 ...     for i in range(0, 10):

File sorl/thumbnail/tests/utils.py

 except NameError:
     from sets import Set as set     # For Python 2.3
 
-utils_tests = """
+MEDIA_ROOT_LENGTH = len(os.path.normpath(settings.MEDIA_ROOT))
+
+utils_tests = r"""
 >>> from sorl.thumbnail.tests.utils import *
 >>> from sorl.thumbnail.tests.base import ChangeSettings
 >>> from django.conf import settings
 
 >>> media_root = settings.MEDIA_ROOT.rstrip('/')
 
-#===============================================================================
+#==============================================================================
 # Set up test images
-#===============================================================================
+#==============================================================================
 
 >>> make_image('test-thumbnail-utils/subdir/test_jpg_110x110_q85.jpg')
 >>> make_image('test-thumbnail-utils/test_jpg_80x80_q85.jpg')
 >>> make_image('test-thumbnail-utils/test_jpg_80x80_q95.jpg')
 >>> make_image('test-thumbnail-utils/another_test_jpg_80x80_q85.jpg')
 >>> make_image('test-thumbnail-utils/test_with_opts_jpg_80x80_crop_bw_q85.jpg')
->>> make_image('test-thumbnail-basedir/test-thumbnail-utils/test_jpg_100x100_q85.jpg')
+>>> make_image('test-thumbnail-basedir/test-thumbnail-utils/test_jpg_100x100_'
+...            'q85.jpg')
 >>> make_image('test-thumbnail-utils/prefix-test_jpg_120x120_q85.jpg')
 
-#===============================================================================
+#==============================================================================
 # all_thumbnails()
-#===============================================================================
+#==============================================================================
 
 # Find all thumbs
 >>> thumb_dir = os.path.join(settings.MEDIA_ROOT, 'test-thumbnail-utils')
 >>> k = thumbs.keys()
 >>> k.sort()
 >>> [consistent_slash(path) for path in k]
-['another_test.jpg', 'prefix-test.jpg', 'subdir/test.jpg', 'test.jpg', 'test_with_opts.jpg']
+['another_test.jpg', 'prefix-test.jpg', 'subdir/test.jpg', 'test.jpg',
+ 'test_with_opts.jpg']
 
 # Find all thumbs, no recurse
 >>> thumbs = all_thumbnails(thumb_dir, recursive=False)
 >>> k
 ['another_test.jpg', 'prefix-test.jpg', 'test.jpg', 'test_with_opts.jpg']
 
-#===============================================================================
+#==============================================================================
 # thumbnails_for_file()
-#===============================================================================
+#==============================================================================
 
 >>> output = []
 >>> for thumb in thumbs['test.jpg']:
 ...     output.append('%(x)sx%(y)s %(quality)s %(rel_fn)s' % thumb)
 >>> output.sort()
 >>> output
-['80x80 85 test-thumbnail-utils/test_jpg_80x80_q85.jpg', '80x80 95 test-thumbnail-utils/test_jpg_80x80_q95.jpg']
+['80x80 85 test-thumbnail-utils/test_jpg_80x80_q85.jpg',
+ '80x80 95 test-thumbnail-utils/test_jpg_80x80_q95.jpg']
 
 # Thumbnails for file
 >>> output = []
 ...    output.append(strip_media_root(thumb['filename']))
 >>> output.sort()
 >>> output
-['test-thumbnail-utils/test_jpg_80x80_q85.jpg', 'test-thumbnail-utils/test_jpg_80x80_q95.jpg']
+['test-thumbnail-utils/test_jpg_80x80_q85.jpg',
+ 'test-thumbnail-utils/test_jpg_80x80_q95.jpg']
 
 # Thumbnails for file - shouldn't choke on non-existant file
 >>> thumbnails_for_file('test-thumbnail-utils/non-existant.jpg')
 ...    print strip_media_root(thumb['filename'])
 test-thumbnail-utils/prefix-test_jpg_120x120_q85.jpg
 
-#===============================================================================
+#==============================================================================
 # Clean up images / directories
-#===============================================================================
+#==============================================================================
 
 >>> clean_up()
 """
 images_to_delete = set()
 dirs_to_delete = []
 
+
 def make_image(relative_image):
     absolute_image = os.path.join(settings.MEDIA_ROOT, relative_image)
     make_dirs(os.path.dirname(relative_image))
     open(absolute_image, 'w').close()
     images_to_delete.add(absolute_image)
 
+
 def make_dirs(relative_path):
     if not relative_path:
         return
     make_dirs(os.path.dirname(relative_path))
     os.mkdir(absolute_path)
 
+
 def clean_up():
     for image in images_to_delete:
         os.remove(image)
     for path in dirs_to_delete:
         os.rmdir(path)
 
-MEDIA_ROOT_LENGTH = len(os.path.normpath(settings.MEDIA_ROOT))
+
 def strip_media_root(path):
     path = os.path.normpath(path)
     # chop off the MEDIA_ROOT and strip any leading os.sep
     path = path[MEDIA_ROOT_LENGTH:].lstrip(os.sep)
     return consistent_slash(path)
 
+
 def consistent_slash(path):
     """
     Ensure we're always testing against the '/' os separator (otherwise tests

File sorl/thumbnail/utils.py

 import os
 
 
-re_thumbnail_file = re.compile(r'(?P<source_filename>.+)_(?P<x>\d+)x(?P<y>\d+)(?:_(?P<options>\w+))?_q(?P<quality>\d+)(?:.[^.]+)?$')
+re_thumbnail_file = re.compile(r'(?P<source_filename>.+)_(?P<x>\d+)x(?P<y>\d+)'
+                               r'(?:_(?P<options>\w+))?_q(?P<quality>\d+)'
+                               r'(?:.[^.]+)?$')
 re_new_args = re.compile('(?<!quality)=')
 
 
             # '.'.
             m = re.match(r'(.*)_(.*)', source_filename)
             if m:
-                 source_filename = '%s.%s' % m.groups()
+                source_filename = '%s.%s' % m.groups()
             filename = os.path.join(rel_dir, source_filename)
             thumbnail_file = thumbnail_files.setdefault(filename, [])
             d['filename'] = os.path.join(dir_, file)
     """
     Split a list of argument strings into a dictionary where each key is an
     argument name.
-    
+
     An argument looks like ``crop``, ``crop="some option"`` or ``crop=my_var``.
     Arguments which provide no value get a value of ``None``.
     """