desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Test that a file can be found and contains the correct content.'
| def _test_found(self, **kwargs):
| response = serve_static(self.request, self.filename, **kwargs)
self.assertEqual(response.status_code, 200)
self.assertTrue(self.storage.exists(self.filename))
if hasattr(response, u'streaming_content'):
content = ''.join(response.streaming_content)
else:
content = response.content
with self.storage.open(self.filename) as f:
self.assertEqual(f.read(), content)
|
'Test that a file could not be found.'
| def _test_not_found(self, filename):
| self.assertFalse(self.storage.exists(filename))
with self.assertRaises(Http404):
serve_static(self.request, filename)
self.assertFalse(self.storage.exists(filename))
|
'Testing PipelineFormMedia.css_packages with PIPELINE_ENABLED=True'
| @pipeline_settings(PIPELINE_ENABLED=True)
def test_css_packages_with_pipeline_enabled(self):
| class MyMedia(PipelineFormMedia, ):
css_packages = {u'all': (u'styles1', u'styles2'), u'print': (u'print',)}
css = {u'all': (u'extra1.css', u'extra2.css')}
media = Media(MyMedia)
self.assertEqual(MyMedia.css, {u'all': [u'extra1.css', u'extra2.css', u'/static/styles1.min.css', u'/static/styles2.min.css'], u'print': [u'/static/print.min.css']})
self.assertEqual(MyMedia.css, media._css)
self.assertEqual(list(media.render_css()), ([(u'<link href="%s" type="text/css" media="all" rel="stylesheet" />' % path) for path in (u'/static/extra1.css', u'/static/extra2.css', u'/static/styles1.min.css', u'/static/styles2.min.css')] + [u'<link href="/static/print.min.css" type="text/css" media="print" rel="stylesheet" />']))
|
'Testing PipelineFormMedia.css_packages with PIPELINE_ENABLED=False'
| @pipeline_settings(PIPELINE_ENABLED=False)
def test_css_packages_with_pipeline_disabled(self):
| class MyMedia(PipelineFormMedia, ):
css_packages = {u'all': (u'styles1', u'styles2'), u'print': (u'print',)}
css = {u'all': (u'extra1.css', u'extra2.css')}
media = Media(MyMedia)
self.assertEqual(MyMedia.css, {u'all': [u'extra1.css', u'extra2.css', u'pipeline/css/first.css', u'pipeline/css/second.css', u'pipeline/css/unicode.css'], u'print': [u'pipeline/css/urls.css']})
self.assertEqual(MyMedia.css, media._css)
self.assertEqual(list(media.render_css()), ([(u'<link href="%s" type="text/css" media="all" rel="stylesheet" />' % path) for path in (u'/static/extra1.css', u'/static/extra2.css', u'/static/pipeline/css/first.css', u'/static/pipeline/css/second.css', u'/static/pipeline/css/unicode.css')] + [u'<link href="/static/pipeline/css/urls.css" type="text/css" media="print" rel="stylesheet" />']))
|
'Testing PipelineFormMedia.js_packages with PIPELINE_ENABLED=True'
| @pipeline_settings(PIPELINE_ENABLED=True)
def test_js_packages_with_pipeline_enabled(self):
| class MyMedia(PipelineFormMedia, ):
js_packages = (u'scripts1', u'scripts2')
js = (u'extra1.js', u'extra2.js')
media = Media(MyMedia)
self.assertEqual(MyMedia.js, [u'extra1.js', u'extra2.js', u'/static/scripts1.min.js', u'/static/scripts2.min.js'])
self.assertEqual(MyMedia.js, media._js)
self.assertEqual(media.render_js(), [(u'<script type="text/javascript" src="%s"></script>' % path) for path in (u'/static/extra1.js', u'/static/extra2.js', u'/static/scripts1.min.js', u'/static/scripts2.min.js')])
|
'Testing PipelineFormMedia.js_packages with PIPELINE_ENABLED=False'
| @pipeline_settings(PIPELINE_ENABLED=False)
def test_js_packages_with_pipeline_disabled(self):
| class MyMedia(PipelineFormMedia, ):
js_packages = (u'scripts1', u'scripts2')
js = (u'extra1.js', u'extra2.js')
media = Media(MyMedia)
self.assertEqual(MyMedia.js, [u'extra1.js', u'extra2.js', u'pipeline/js/first.js', u'pipeline/js/second.js', u'pipeline/js/application.js'])
self.assertEqual(MyMedia.js, media._js)
self.assertEqual(media.render_js(), [(u'<script type="text/javascript" src="%s"></script>' % path) for path in (u'/static/extra1.js', u'/static/extra2.js', u'/static/pipeline/js/first.js', u'/static/pipeline/js/second.js', u'/static/pipeline/js/application.js')])
|
'Title shown in the side bar. Defaults to :attr:`title`.'
| @property
def nav_title(self):
| return self.title
|
'Subtitle shown in the side bar. Defaults to the empty string.'
| @property
def nav_subtitle(self):
| return u''
|
'``True`` if the panel can be displayed in full screen, ``False`` if
it\'s only shown in the side bar. Defaults to ``True``.'
| @property
def has_content(self):
| return True
|
'Title shown in the panel when it\'s displayed in full screen.
Mandatory, unless the panel sets :attr:`has_content` to ``False``.'
| @property
def title(self):
| raise NotImplementedError
|
'Template used to render :attr:`content`.
Mandatory, unless the panel sets :attr:`has_content` to ``False`` or
overrides `attr`:content`.'
| @property
def template(self):
| raise NotImplementedError
|
'Content of the panel when it\'s displayed in full screen.
By default this renders the template defined by :attr:`template`.
Statistics stored with :meth:`record_stats` are available in the
template\'s context.'
| @property
def content(self):
| if self.has_content:
return render_to_string(self.template, self.get_stats())
|
'Return URLpatterns, if the panel has its own views.'
| @classmethod
def get_urls(cls):
| return []
|
'Store data gathered by the panel. ``stats`` is a :class:`dict`.
Each call to ``record_stats`` updates the statistics dictionary.'
| def record_stats(self, stats):
| self.toolbar.stats.setdefault(self.panel_id, {}).update(stats)
|
'Access data stored by the panel. Returns a :class:`dict`.'
| def get_stats(self):
| return self.toolbar.stats.get(self.panel_id, {})
|
'Returns a sorted mapping between the finder path and the list
of relative and file system paths which that finder was able
to find.'
| def get_staticfiles_finders(self):
| finders_mapping = OrderedDict()
for finder in finders.get_finders():
for (path, finder_storage) in finder.list([]):
if getattr(finder_storage, u'prefix', None):
prefixed_path = join(finder_storage.prefix, path)
else:
prefixed_path = path
finder_cls = finder.__class__
finder_path = u'.'.join([finder_cls.__module__, finder_cls.__name__])
real_path = finder_storage.path(path)
payload = (prefixed_path, real_path)
finders_mapping.setdefault(finder_path, []).append(payload)
self.num_found += 1
return finders_mapping
|
'Returns a list of paths to inspect for additional static files'
| def get_staticfiles_dirs(self):
| dirs = []
for finder in finders.get_finders():
if isinstance(finder, finders.FileSystemFinder):
dirs.extend(finder.locations)
return [(prefix, normpath(dir)) for (prefix, dir) in dirs]
|
'Returns a list of app paths that have a static directory'
| def get_staticfiles_apps(self):
| apps = []
for finder in finders.get_finders():
if isinstance(finder, finders.AppDirectoriesFinder):
for app in finder.apps:
if (app not in apps):
apps.append(app)
return apps
|
'Process the token stream'
| def process(self, stream):
| for (token_type, value) in stream:
is_keyword = (token_type in T.Keyword)
if is_keyword:
(yield (T.Text, u'<strong>'))
(yield (token_type, escape(value)))
if is_keyword:
(yield (T.Text, u'</strong>'))
|
'Show abbreviated name of view function as subtitle'
| @property
def nav_subtitle(self):
| view_func = self.get_stats().get(u'view_func', u'')
return view_func.rsplit(u'.', 1)[(-1)]
|
'Returns a list of collected items for the provided thread, of if none
is provided, returns a list for the current thread.'
| def get_collection(self, thread=None):
| if (thread is None):
thread = threading.currentThread()
if (thread not in self.collections):
self.collections[thread] = []
return self.collections[thread]
|
'Get a list of all available panels.'
| @property
def panels(self):
| return list(self._panels.values())
|
'Get a list of panels enabled for the current request.'
| @property
def enabled_panels(self):
| return [panel for panel in self._panels.values() if panel.enabled]
|
'Get the panel with the given id, which is the class name by default.'
| def get_panel_by_id(self, panel_id):
| return self._panels[panel_id]
|
'Renders the overall Toolbar with panels inside.'
| def render_toolbar(self):
| if (not self.should_render_panels()):
self.store()
try:
context = {u'toolbar': self}
return render_to_string(u'debug_toolbar/base.html', context)
except TemplateSyntaxError:
if (not apps.is_installed(u'django.contrib.staticfiles')):
raise ImproperlyConfigured(u"The debug toolbar requires the staticfiles contrib app. Add 'django.contrib.staticfiles' to INSTALLED_APPS and define STATIC_URL in your settings.")
else:
raise
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| redirect = HttpResponse(status=304)
response = self.panel.process_response(self.request, redirect)
self.assertIsNotNone(response)
response = self.panel.generate_stats(self.request, redirect)
self.assertIsNone(response)
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| self.request.path = u'/non_ascii_request/'
self.panel.process_response(self.request, self.response)
self.assertNotIn(u'n\xf4t \xe5sc\xed\xec', self.panel.content)
self.panel.generate_stats(self.request, self.response)
self.assertIn(u'n\xf4t \xe5sc\xed\xec', self.panel.content)
self.assertValidHTML(self.panel.content)
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| self.logger.info(u'caf\xe9')
self.panel.process_response(self.request, self.response)
self.assertNotIn(u'caf\xe9', self.panel.content)
self.panel.generate_stats(self.request, self.response)
self.assertIn(u'caf\xe9', self.panel.content)
self.assertValidHTML(self.panel.content)
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| t = Template(u'{{ object }}')
c = Context({u'object': NonAsciiRepr()})
t.render(c)
self.panel.process_response(self.request, self.response)
self.assertNotIn(u'n\xf4t \xe5sc\xed\xec', self.panel.content)
self.panel.generate_stats(self.request, self.response)
self.assertIn(u'n\xf4t \xe5sc\xed\xec', self.panel.content)
self.assertValidHTML(self.panel.content)
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| list(User.objects.filter(username=u'caf\xe9'.encode(u'utf-8')))
self.panel.process_response(self.request, self.response)
self.assertNotIn(u'caf\xe9', self.panel.content)
self.panel.generate_stats(self.request, self.response)
self.assertIn(u'caf\xe9', self.panel.content)
self.assertValidHTML(self.panel.content)
|
'Test that an error in the query isn\'t swallowed by the middleware.'
| @unittest.skipUnless((connection.vendor == u'postgresql'), u'Test valid only on PostgreSQL')
def test_erroneous_query(self):
| try:
connection.cursor().execute(u'erroneous query')
except DatabaseError as e:
self.assertTrue((u'erroneous query' in str(e)))
|
'Test case for when the template loader runs a SQL query that causes
an infinite recursion in the SQL panel.'
| @override_settings(DEBUG=True, TEMPLATES=[{u'BACKEND': u'django.template.backends.django.DjangoTemplates', u'OPTIONS': {u'debug': True, u'loaders': [u'tests.loaders.LoaderWithSQL']}}])
def test_regression_infinite_recursion(self):
| self.assertEqual(len(self.panel._queries), 0)
render(self.request, u'basic.html', {})
self.assertEqual(len(self.panel._queries), 2)
query = self.panel._queries[0]
self.assertEqual(query[0], u'default')
self.assertTrue((u'sql' in query[1]))
self.assertTrue((u'duration' in query[1]))
self.assertTrue((u'stacktrace' in query[1]))
self.assertTrue((len(query[1][u'stacktrace']) > 0))
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| self.panel.process_request(self.request)
self.panel.process_response(self.request, self.response)
self.assertNotIn(u'django.contrib.staticfiles.finders.AppDirectoriesFinder', self.panel.content)
self.panel.generate_stats(self.request, self.response)
self.assertIn(u'django.contrib.staticfiles.finders.AppDirectoriesFinder', self.panel.content)
self.assertValidHTML(self.panel.content)
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| cache.cache.get(u'caf\xe9')
self.panel.process_response(self.request, self.response)
self.assertNotIn(u'caf\xe9', self.panel.content)
self.panel.generate_stats(self.request, self.response)
self.assertIn(u'caf\xe9', self.panel.content)
self.assertValidHTML(self.panel.content)
|
'Test that the panel only inserts content after generate_stats and
not the process_response.'
| def test_insert_content(self):
| self.panel.process_view(self.request, regular_view, (u'profiling',), {})
self.panel.process_response(self.request, self.response)
self.assertNotIn(u'regular_view', self.panel.content)
self.panel.generate_stats(self.request, self.response)
self.assertIn(u'regular_view', self.panel.content)
self.assertValidHTML(self.panel.content)
|
'Creates an image and prepends the MEDIA ROOT path.
:param name: e.g. 500x500.jpg
:param dim: a dimension tuple e.g. (500, 500)'
| def create_image(self, name, dim, transparent=False):
| filename = os.path.join(settings.MEDIA_ROOT, name)
im = Image.new(u'L', dim)
if transparent:
draw = ImageDraw.Draw(im)
draw.line(((0, 0) + im.size), fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
im.save(filename, transparency=0)
else:
im.save(filename)
return Item.objects.get_or_create(image=name)
|
'If source image does not exists, properly close all file descriptors'
| def test_no_source_get_image(self):
| source = ImageFile('nonexistent.jpeg')
with same_open_fd_count(self):
with self.assertRaises(IOError):
self.ENGINE.get_image(source)
|
'Only the KV store is cleared.'
| def test_clear_action(self):
| (name1, name2) = self.make_test_thumbnails('400x300', '200x200')
out = StringIO('')
management.call_command('thumbnail', 'clear', verbosity=1, stdout=out)
self.assertEqual(out.getvalue(), 'Clear the Key Value Store ... [Done]\n')
self.assertTrue(os.path.isfile(name1))
self.assertTrue(os.path.isfile(name2))
|
'Clear KV store and delete referenced thumbnails'
| def test_clear_delete_referenced_action(self):
| (name1, name2) = self.make_test_thumbnails('400x300', '200x200')
management.call_command('thumbnail', 'clear', verbosity=0)
(name3,) = self.make_test_thumbnails('100x100')
out = StringIO('')
management.call_command('thumbnail', 'clear_delete_referenced', verbosity=1, stdout=out)
lines = out.getvalue().split('\n')
self.assertEqual(lines[0], 'Delete all thumbnail files referenced in Key Value Store ... [Done]')
self.assertEqual(lines[1], 'Clear the Key Value Store ... [Done]')
self.assertTrue(os.path.isfile(name1))
self.assertTrue(os.path.isfile(name2))
self.assertFalse(os.path.isfile(name3))
|
'Clear KV store and delete all thumbnails'
| def test_clear_delete_all_action(self):
| (name1, name2) = self.make_test_thumbnails('400x300', '200x200')
management.call_command('thumbnail', 'clear', verbosity=0)
(name3,) = self.make_test_thumbnails('100x100')
out = StringIO('')
management.call_command('thumbnail', 'clear_delete_all', verbosity=1, stdout=out)
lines = out.getvalue().split('\n')
self.assertEqual(lines[0], 'Clear the Key Value Store ... [Done]')
self.assertEqual(lines[1], 'Delete all thumbnail files in THUMBNAIL_PREFIX ... [Done]')
self.assertFalse(os.path.isfile(name1))
self.assertFalse(os.path.isfile(name2))
self.assertFalse(os.path.isfile(name3))
|
'Test that is_valid_image returns false for a truncated image.'
| @unittest.skip(u'See issue #427')
def test_truncated_validation(self):
| name = u'data/broken.jpeg'
with open(name, u'rb') as broken_jpeg:
data = broken_jpeg.read()
engine = PILEngine()
self.assertFalse(engine.is_valid_image(data))
|
'Confirm that generating a thumbnail for our "broken" image fails.'
| @unittest.skip(u'See issue #427. This seems to not-fail with wand')
def test_truncated_generation_failure(self):
| name = u'data/broken.jpeg'
with open(name, u'rb') as broken_jpeg:
with self.assertRaises((OSError, IOError)):
im = default.engine.get_image(broken_jpeg)
options = ThumbnailBackend.default_options
ratio = default.engine.get_image_ratio(im, options)
geometry = parse_geometry(u'120x120', ratio)
default.engine.create(im, geometry, options)
|
'Returns thumbnail as an ImageFile instance for file with geometry and
options given. First it will try to get it from the key value store,
secondly it will create it.'
| def get_thumbnail(self, file_, geometry_string, **options):
| logger.debug(u'Getting thumbnail for file [%s] at [%s]', file_, geometry_string)
if file_:
source = ImageFile(file_)
elif settings.THUMBNAIL_DUMMY:
return DummyImageFile(geometry_string)
else:
logger.error(u'missing file_ argument in get_thumbnail()')
return
if settings.THUMBNAIL_PRESERVE_FORMAT:
options.setdefault(u'format', self._get_format(source))
for (key, value) in self.default_options.items():
options.setdefault(key, value)
for (key, attr) in self.extra_options:
value = getattr(settings, attr)
if (value != getattr(default_settings, attr)):
options.setdefault(key, value)
name = self._get_thumbnail_filename(source, geometry_string, options)
thumbnail = ImageFile(name, default.storage)
cached = default.kvstore.get(thumbnail)
if cached:
return cached
if (settings.THUMBNAIL_FORCE_OVERWRITE or (not thumbnail.exists())):
try:
source_image = default.engine.get_image(source)
except IOError as e:
logger.exception(e)
if settings.THUMBNAIL_DUMMY:
return DummyImageFile(geometry_string)
else:
logger.warning(u'Remote file [%s] at [%s] does not exist', file_, geometry_string)
return thumbnail
image_info = default.engine.get_image_info(source_image)
options[u'image_info'] = image_info
size = default.engine.get_image_size(source_image)
source.set_size(size)
try:
self._create_thumbnail(source_image, geometry_string, options, thumbnail)
self._create_alternative_resolutions(source_image, geometry_string, options, thumbnail.name)
finally:
default.engine.cleanup(source_image)
default.kvstore.get_or_set(source)
default.kvstore.set(thumbnail, source)
return thumbnail
|
'Deletes file_ references in Key Value store and optionally the file_
it self.'
| def delete(self, file_, delete_file=True):
| image_file = ImageFile(file_)
if delete_file:
image_file.delete()
default.kvstore.delete(image_file)
|
'Creates the thumbnail by using default.engine'
| def _create_thumbnail(self, source_image, geometry_string, options, thumbnail):
| logger.debug(u'Creating thumbnail file [%s] at [%s] with [%s]', thumbnail.name, geometry_string, options)
ratio = default.engine.get_image_ratio(source_image, options)
geometry = parse_geometry(geometry_string, ratio)
image = default.engine.create(source_image, geometry, options)
default.engine.write(image, options, thumbnail)
size = default.engine.get_image_size(image)
thumbnail.set_size(size)
|
'Creates the thumbnail by using default.engine with multiple output
sizes. Appends @<ratio>x to the file name.'
| def _create_alternative_resolutions(self, source_image, geometry_string, options, name):
| ratio = default.engine.get_image_ratio(source_image, options)
geometry = parse_geometry(geometry_string, ratio)
(file_name, dot_file_ext) = os.path.splitext(name)
for resolution in settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS:
resolution_geometry = (int((geometry[0] * resolution)), int((geometry[1] * resolution)))
resolution_options = options.copy()
if ((u'crop' in options) and isinstance(options[u'crop'], string_types)):
crop = options[u'crop'].split(u' ')
for i in range(len(crop)):
s = re.match(u'(\\d+)px', crop[i])
if s:
crop[i] = (u'%spx' % int((int(s.group(1)) * resolution)))
resolution_options[u'crop'] = u' '.join(crop)
image = default.engine.create(source_image, resolution_geometry, options)
thumbnail_name = (u'%(file_name)s%(suffix)s%(file_ext)s' % {u'file_name': file_name, u'suffix': (u'@%sx' % resolution), u'file_ext': dot_file_ext})
thumbnail = ImageFile(thumbnail_name, default.storage)
default.engine.write(image, resolution_options, thumbnail)
size = default.engine.get_image_size(image)
thumbnail.set_size(size)
|
'Computes the destination filename.'
| def _get_thumbnail_filename(self, source, geometry_string, options):
| key = tokey(source.key, geometry_string, serialize(options))
path = (u'%s/%s/%s' % (key[:2], key[2:4], key))
return (u'%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options[u'format']]))
|
'Adds deletion of thumbnails and key value store references to the
parent class implementation. Only called in Django < 1.2.5'
| def delete_file(self, instance, sender, **kwargs):
| file_ = getattr(instance, self.attname)
query = (Q(**{self.name: file_.name}) & (~ Q(pk=instance.pk)))
qs = sender._default_manager.filter(query)
if (file_ and (file_.name != self.default) and (not qs)):
default.backend.delete(file_)
elif file_:
file_.close()
|
'Checks that the file-upload field data contains a valid image (GIF,
JPG, PNG, possibly others -- whatever the engine supports).'
| def to_python(self, data):
| f = super(ImageFormField, self).to_python(data)
if (f is None):
return None
if hasattr(data, u'temporary_file_path'):
with open(data.temporary_file_path(), u'rb') as fp:
raw_data = fp.read()
elif hasattr(data, u'read'):
raw_data = data.read()
else:
raw_data = data[u'content']
if (not default.engine.is_valid_image(raw_data)):
raise forms.ValidationError(self.default_error_messages[u'invalid_image'])
if (hasattr(f, u'seek') and callable(f.seek)):
f.seek(0)
return f
|
'We can clear the database more efficiently using the prefix here rather
than calling :meth:`_delete_raw`.'
| def clear(self, delete_thumbnails=False):
| prefix = settings.THUMBNAIL_KEY_PREFIX
for key in self._find_keys_raw(prefix):
self.cache.delete(key)
KVStoreModel.objects.filter(key__startswith=prefix).delete()
if delete_thumbnails:
self.delete_all_thumbnail_files()
|
'Gets the ``image_file`` from store. Returns ``None`` if not found.'
| def get(self, image_file):
| return self._get(image_file.key)
|
'Updates store for the `image_file`. Makes sure the `image_file` has a
size set.'
| def set(self, image_file, source=None):
| image_file.set_size()
self._set(image_file.key, image_file)
if (source is not None):
if (not self.get(source)):
raise ThumbnailError((u'Cannot add thumbnails for source: `%s` that is not in kvstore.' % source.name))
thumbnails = (self._get(source.key, identity=u'thumbnails') or [])
thumbnails = set(thumbnails)
thumbnails.add(image_file.key)
self._set(source.key, list(thumbnails), identity=u'thumbnails')
|
'Deletes the reference to the ``image_file`` and deletes the references
to thumbnails as well as thumbnail files if ``delete_thumbnails`` is
`True``. Does not delete the ``image_file`` is self.'
| def delete(self, image_file, delete_thumbnails=True):
| if delete_thumbnails:
self.delete_thumbnails(image_file)
self._delete(image_file.key)
|
'Deletes references to thumbnails as well as thumbnail ``image_files``.'
| def delete_thumbnails(self, image_file):
| thumbnail_keys = self._get(image_file.key, identity=u'thumbnails')
if thumbnail_keys:
for key in thumbnail_keys:
thumbnail = self._get(key)
if thumbnail:
self.delete(thumbnail, False)
thumbnail.delete()
self._delete(image_file.key, identity=u'thumbnails')
|
'Cleans up the key value store. In detail:
1. Deletes all key store references for image_files that do not exist
and all key references for its thumbnails *and* their image_files.
2. Deletes or updates all invalid thumbnail keys'
| def cleanup(self):
| for key in self._find_keys(identity=u'image'):
image_file = self._get(key)
if (image_file and (not image_file.exists())):
self.delete(image_file)
for key in self._find_keys(identity=u'thumbnails'):
image_file = self._get(key)
if image_file:
thumbnail_keys = (self._get(key, identity=u'thumbnails') or [])
thumbnail_keys_set = set(thumbnail_keys)
for thumbnail_key in thumbnail_keys:
if (not self._get(thumbnail_key)):
thumbnail_keys_set.remove(thumbnail_key)
thumbnail_keys = list(thumbnail_keys_set)
if thumbnail_keys:
self._set(key, thumbnail_keys, identity=u'thumbnails')
continue
self._delete(key, identity=u'thumbnails')
|
'Brutely clears the key value store for keys with THUMBNAIL_KEY_PREFIX
prefix. Use this in emergency situations. Normally you would probably
want to use the ``cleanup`` method instead.'
| def clear(self):
| all_keys = self._find_keys_raw(settings.THUMBNAIL_KEY_PREFIX)
if all_keys:
self._delete_raw(*all_keys)
|
'Deserializing, prefix wrapper for _get_raw'
| def _get(self, key, identity=u'image'):
| value = self._get_raw(add_prefix(key, identity))
if (not value):
return None
if (identity == u'image'):
return deserialize_image_file(value)
return deserialize(value)
|
'Serializing, prefix wrapper for _set_raw'
| def _set(self, key, value, identity=u'image'):
| if (identity == u'image'):
s = serialize_image_file(value)
else:
s = serialize(value)
self._set_raw(add_prefix(key, identity), s)
|
'Prefix wrapper for _delete_raw'
| def _delete(self, key, identity=u'image'):
| self._delete_raw(add_prefix(key, identity))
|
'Finds and returns all keys for identity,'
| def _find_keys(self, identity=u'image'):
| prefix = add_prefix(u'', identity)
raw_keys = (self._find_keys_raw(prefix) or [])
for raw_key in raw_keys:
(yield del_prefix(raw_key))
|
'Gets the value from keystore, returns `None` if not found.'
| def _get_raw(self, key):
| raise NotImplementedError()
|
'Sets value associated to key. Key is expected to be shorter than 200
chars. Value is a ``unicode`` object with an unknown (reasonable)
length.'
| def _set_raw(self, key, value):
| raise NotImplementedError()
|
'Deletes the keys. Silent failure for missing keys.'
| def _delete_raw(self, *keys):
| raise NotImplementedError()
|
'Finds all keys with prefix'
| def _find_keys_raw(self, prefix):
| raise NotImplementedError()
|
'Do not manipulate image, but ask engine whether we\'d be doing a 90deg
rotation at some point.'
| def flip_dimensions(self, image):
| return default.engine.flip_dimensions(image)
|
'Processing conductor, returns the thumbnail as an image engine instance'
| def create(self, image, geometry, options):
| image = self.cropbox(image, geometry, options)
image = self.orientation(image, geometry, options)
image = self.colorspace(image, geometry, options)
image = self.remove_border(image, options)
image = self.scale(image, geometry, options)
image = self.crop(image, geometry, options)
image = self.rounded(image, geometry, options)
image = self.blur(image, geometry, options)
image = self.padding(image, geometry, options)
return image
|
'Wrapper for ``_cropbox``'
| def cropbox(self, image, geometry, options):
| cropbox = options['cropbox']
if (not cropbox):
return image
(x, y, x2, y2) = parse_cropbox(cropbox)
return self._cropbox(image, x, y, x2, y2)
|
'Wrapper for ``_orientation``'
| def orientation(self, image, geometry, options):
| if options.get('orientation', settings.THUMBNAIL_ORIENTATION):
return self._orientation(image)
self.reoriented = True
return image
|
'Wrapper for ``_colorspace``'
| def colorspace(self, image, geometry, options):
| colorspace = options['colorspace']
return self._colorspace(image, colorspace)
|
'Wrapper for ``_scale``'
| def scale(self, image, geometry, options):
| upscale = options['upscale']
(x_image, y_image) = map(float, self.get_image_size(image))
factor = self._calculate_scaling_factor(x_image, y_image, geometry, options)
if ((factor < 1) or upscale):
width = toint((x_image * factor))
height = toint((y_image * factor))
image = self._scale(image, width, height)
return image
|
'Wrapper for ``_crop``'
| def crop(self, image, geometry, options):
| crop = options['crop']
(x_image, y_image) = self.get_image_size(image)
if ((not crop) or (crop == 'noop')):
return image
elif (crop == 'smart'):
return self._entropy_crop(image, geometry[0], geometry[1], x_image, y_image)
geometry = (min(x_image, geometry[0]), min(y_image, geometry[1]))
(x_offset, y_offset) = parse_crop(crop, (x_image, y_image), geometry)
return self._crop(image, geometry[0], geometry[1], x_offset, y_offset)
|
'Wrapper for ``_rounded``'
| def rounded(self, image, geometry, options):
| r = options['rounded']
if (not r):
return image
return self._rounded(image, int(r))
|
'Wrapper for ``_blur``'
| def blur(self, image, geometry, options):
| if options.get('blur'):
return self._blur(image, int(options.get('blur')))
return image
|
'Wrapper for ``_padding``'
| def padding(self, image, geometry, options):
| if (options.get('padding') and (self.get_image_size(image) != geometry)):
return self._padding(image, geometry, options)
return image
|
'Wrapper for ``_write``'
| def write(self, image, options, thumbnail):
| format_ = options['format']
quality = options['quality']
image_info = options.get('image_info', {})
progressive = options.get('progressive', settings.THUMBNAIL_PROGRESSIVE)
raw_data = self._get_raw_data(image, format_, quality, image_info=image_info, progressive=progressive)
thumbnail.write(raw_data)
|
'Some backends need to manually cleanup after thumbnails are created'
| def cleanup(self, image):
| pass
|
'Calculates the image ratio. If cropbox option is used, the ratio
may have changed.'
| def get_image_ratio(self, image, options):
| cropbox = options['cropbox']
if cropbox:
(x, y, x2, y2) = parse_cropbox(cropbox)
x = (x2 - x)
y = (y2 - y)
else:
(x, y) = self.get_image_size(image)
return (float(x) / y)
|
'Returns metadata of an ImageFile instance'
| def get_image_info(self, image):
| return {}
|
'Returns the backend image objects from an ImageFile instance'
| def get_image(self, source):
| raise NotImplementedError()
|
'Returns the image width and height as a tuple'
| def get_image_size(self, image):
| raise NotImplementedError()
|
'Checks if the supplied raw data is valid image data'
| def is_valid_image(self, raw_data):
| raise NotImplementedError()
|
'Read orientation exif data and orientate the image accordingly'
| def _orientation(self, image):
| return image
|
'`Valid colorspaces
<http://www.graphicsmagick.org/GraphicsMagick.html#details-colorspace>`_.
Backends need to implement the following::
RGB, GRAY'
| def _colorspace(self, image, colorspace):
| raise NotImplementedError()
|
'Remove borders around images'
| def _remove_border(self, image, image_width, image_height):
| raise NotImplementedError()
|
'Crop the image to the correct aspect ratio
by removing the lowest entropy parts'
| def _entropy_crop(self, image, geometry_width, geometry_height, image_width, image_height):
| raise NotImplementedError()
|
'Does the resizing of the image'
| def _scale(self, image, width, height):
| raise NotImplementedError()
|
'Crops the image'
| def _crop(self, image, width, height, x_offset, y_offset):
| raise NotImplementedError()
|
'Gets raw data given the image, format and quality. This method is
called from :meth:`write`'
| def _get_raw_data(self, image, format_, quality, image_info=None, progressive=False):
| raise NotImplementedError()
|
'Pads the image'
| def _padding(self, image, geometry, options):
| raise NotImplementedError()
|
'Writes the thumbnail image'
| def write(self, image, options, thumbnail):
| if ((options[u'format'] == u'JPEG') and options.get(u'progressive', settings.THUMBNAIL_PROGRESSIVE)):
image[u'options'][u'interlace'] = u'line'
image[u'options'][u'quality'] = options[u'quality']
args = settings.THUMBNAIL_CONVERT.split(u' ')
args.append((image[u'source'] + u'[0]'))
for k in image[u'options']:
v = image[u'options'][k]
args.append((u'-%s' % k))
if (v is not None):
args.append((u'%s' % v))
flatten = u'on'
if (u'flatten' in options):
flatten = options[u'flatten']
if (settings.THUMBNAIL_FLATTEN and (not (flatten == u'off'))):
args.append(u'-flatten')
suffix = (u'.%s' % EXTENSIONS[options[u'format']])
with NamedTemporaryFile(suffix=suffix, mode=u'rb') as fp:
args.append(fp.name)
args = map(smart_str, args)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
returncode = p.wait()
(out, err) = p.communicate()
if returncode:
raise EngineError((u'The command %r exited with a non-zero exit code and printed this to stderr: %s' % (args, err)))
elif err:
logger.error(u'Captured stderr: %s', err)
thumbnail.write(fp.read())
|
'Returns the backend image objects from a ImageFile instance'
| def get_image(self, source):
| with NamedTemporaryFile(mode=u'wb', delete=False) as fp:
fp.write(source.read())
return {u'source': fp.name, u'options': OrderedDict(), u'size': None}
|
'Returns the image width and height as a tuple'
| def get_image_size(self, image):
| if (image[u'size'] is None):
args = settings.THUMBNAIL_IDENTIFY.split(u' ')
args.append(image[u'source'])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
m = size_re.match(str(p.stdout.read()))
image[u'size'] = (int(m.group(u'x')), int(m.group(u'y')))
return image[u'size']
|
'This is not very good for imagemagick because it will say anything is
valid that it can use as input.'
| def is_valid_image(self, raw_data):
| with NamedTemporaryFile(mode=u'wb') as fp:
fp.write(raw_data)
fp.flush()
args = settings.THUMBNAIL_IDENTIFY.split(u' ')
args.append(fp.name)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = p.wait()
return (retcode == 0)
|
'`Valid colorspaces
<http://www.graphicsmagick.org/GraphicsMagick.html#details-colorspace>`_.
Backends need to implement the following::
RGB, GRAY'
| def _colorspace(self, image, colorspace):
| image[u'options'][u'colorspace'] = colorspace
return image
|
'Crops the image'
| def _crop(self, image, width, height, x_offset, y_offset):
| image[u'options'][u'crop'] = (u'%sx%s+%s+%s' % (width, height, x_offset, y_offset))
image[u'size'] = (width, height)
return image
|
'Does the resizing of the image'
| def _scale(self, image, width, height):
| image[u'options'][u'scale'] = (u'%sx%s!' % (width, height))
image[u'size'] = (width, height)
return image
|
'Pads the image'
| def _padding(self, image, geometry, options):
| image[u'options'][u'background'] = options.get(u'padding_color')
image[u'options'][u'gravity'] = u'center'
image[u'options'][u'extent'] = (u'%sx%s' % (geometry[0], geometry[1]))
return image
|
'calculate the entropy of an image'
| def _get_image_entropy(self, image):
| hist = image.histogram()
hist_size = sum(hist)
hist = [(float(h) / hist_size) for h in hist]
return (- sum([(p * math.log(p, 2)) for p in hist if (p != 0)]))
|
'Wand library makes sure when opening any image that is fine, when
the image is corrupted raises an exception.'
| def is_valid_image(self, raw_data):
| try:
Image(blob=raw_data)
return True
except (exceptions.CorruptImageError, exceptions.MissingDelegateError):
return False
|
'Writes the thumbnail image'
| def write(self, image, options, thumbnail):
| args = settings.THUMBNAIL_VIPSTHUMBNAIL.split(u' ')
args.append(image[u'source'])
for k in image[u'options']:
v = image[u'options'][k]
args.append((u'--%s' % k))
if (v is not None):
args.append((u'%s' % v))
suffix = (u'.%s' % EXTENSIONS[options[u'format']])
write_options = []
if ((options[u'format'] == u'JPEG') and options.get(u'progressive', settings.THUMBNAIL_PROGRESSIVE)):
write_options.append(u'interlace')
if options[u'quality']:
if (options[u'format'] == u'JPEG'):
write_options.append((u'Q=%d' % options[u'quality']))
with NamedTemporaryFile(suffix=suffix, mode=u'rb') as fp:
args.append(u'-o')
args.append((fp.name + (u'[%s]' % u','.join(write_options))))
args = map(smart_str, args)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
(out, err) = p.communicate()
if err:
raise Exception(err)
thumbnail.write(fp.read())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.