File: imagekit.py

package info (click to toggle)
python-django-imagekit 5.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 692 kB
  • sloc: python: 1,975; makefile: 133; sh: 6
file content (284 lines) | stat: -rw-r--r-- 10,284 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
from django import template
from django.template.library import parse_bits
from django.utils.encoding import force_str
from django.utils.html import escape
from django.utils.safestring import mark_safe

from ..cachefiles import ImageCacheFile
from ..registry import generator_registry

register = template.Library()


ASSIGNMENT_DELIMETER = 'as'
HTML_ATTRS_DELIMITER = '--'
DEFAULT_THUMBNAIL_GENERATOR = 'imagekit:thumbnail'


def get_cachefile(context, generator_id, generator_kwargs, source=None):
    generator_id = generator_id.resolve(context)
    kwargs = {k: v.resolve(context) for k, v in generator_kwargs.items()}
    generator = generator_registry.get(generator_id, **kwargs)
    return ImageCacheFile(generator)


def parse_dimensions(dimensions):
    """
    Parse the width and height values from a dimension string. Valid values are
    '1x1', '1x', and 'x1'. If one of the dimensions is omitted, the parse result
    will be None for that value.

    """
    width, height = [d.strip() and int(d) or None for d in dimensions.split('x')]
    return {'width': width, 'height': height}


class GenerateImageAssignmentNode(template.Node):

    def __init__(self, variable_name, generator_id, generator_kwargs):
        self._generator_id = generator_id
        self._generator_kwargs = generator_kwargs
        self._variable_name = variable_name

    def get_variable_name(self, context):
        return force_str(self._variable_name)

    def render(self, context):
        variable_name = self.get_variable_name(context)
        context[variable_name] = get_cachefile(context, self._generator_id,
                self._generator_kwargs)
        return ''


class GenerateImageTagNode(template.Node):

    def __init__(self, generator_id, generator_kwargs, html_attrs):
        self._generator_id = generator_id
        self._generator_kwargs = generator_kwargs
        self._html_attrs = html_attrs

    def render(self, context):
        file = get_cachefile(context, self._generator_id,
                self._generator_kwargs)
        attrs = {k: v.resolve(context) for k, v in self._html_attrs.items()}

        # Only add width and height if neither is specified (to allow for
        # proportional in-browser scaling).
        if 'width' not in attrs and 'height' not in attrs:
            attrs.update(width=file.width, height=file.height)

        attrs['src'] = file.url
        attr_str = ' '.join('%s="%s"' % (escape(k), escape(v)) for k, v in
                attrs.items())
        return mark_safe('<img %s />' % attr_str)


class ThumbnailAssignmentNode(template.Node):

    def __init__(self, variable_name, generator_id, dimensions, source, generator_kwargs):
        self._variable_name = variable_name
        self._generator_id = generator_id
        self._dimensions = dimensions
        self._source = source
        self._generator_kwargs = generator_kwargs

    def get_variable_name(self, context):
        return force_str(self._variable_name)

    def render(self, context):
        variable_name = self.get_variable_name(context)

        generator_id = self._generator_id.resolve(context) if self._generator_id else DEFAULT_THUMBNAIL_GENERATOR
        kwargs = {k: v.resolve(context) for k, v in self._generator_kwargs.items()}
        kwargs['source'] = self._source.resolve(context)
        kwargs.update(parse_dimensions(self._dimensions.resolve(context)))
        if kwargs.get('anchor'):
            # ImageKit uses pickle at protocol 0, which throws infinite
            # recursion errors when anchor is set to a SafeString instance.
            # This converts the SafeString into a str instance.
            kwargs['anchor'] = kwargs['anchor'][:]
        generator = generator_registry.get(generator_id, **kwargs)

        context[variable_name] = ImageCacheFile(generator)

        return ''


class ThumbnailImageTagNode(template.Node):

    def __init__(self, generator_id, dimensions, source, generator_kwargs, html_attrs):
        self._generator_id = generator_id
        self._dimensions = dimensions
        self._source = source
        self._generator_kwargs = generator_kwargs
        self._html_attrs = html_attrs

    def render(self, context):
        generator_id = self._generator_id.resolve(context) if self._generator_id else DEFAULT_THUMBNAIL_GENERATOR
        dimensions = parse_dimensions(self._dimensions.resolve(context))
        kwargs = {k: v.resolve(context) for k, v in self._generator_kwargs.items()}
        kwargs['source'] = self._source.resolve(context)
        kwargs.update(dimensions)
        if kwargs.get('anchor'):
            # ImageKit uses pickle at protocol 0, which throws infinite
            # recursion errors when anchor is set to a SafeString instance.
            # This converts the SafeString into a str instance.
            kwargs['anchor'] = kwargs['anchor'][:]
        generator = generator_registry.get(generator_id, **kwargs)

        file = ImageCacheFile(generator)

        attrs = {k: v.resolve(context) for k, v in self._html_attrs.items()}

        # Only add width and height if neither is specified (to allow for
        # proportional in-browser scaling).
        if 'width' not in attrs and 'height' not in attrs:
            attrs.update(width=file.width, height=file.height)

        attrs['src'] = file.url
        attr_str = ' '.join('%s="%s"' % (escape(k), escape(v)) for k, v in
                attrs.items())
        return mark_safe('<img %s />' % attr_str)


def parse_ik_tag_bits(parser, bits):
    """
    Parses the tag name, html attributes and variable name (for assignment tags)
    from the provided bits. The preceding bits may vary and are left to be
    parsed by specific tags.

    """
    varname = None
    html_attrs = {}
    tag_name = bits.pop(0)

    if len(bits) >= 2 and bits[-2] == ASSIGNMENT_DELIMETER:
        varname = bits[-1]
        bits = bits[:-2]

    if HTML_ATTRS_DELIMITER in bits:

        if varname:
            raise template.TemplateSyntaxError('Do not specify html attributes'
                    ' (using "%s") when using the "%s" tag as an assignment'
                    ' tag.' % (HTML_ATTRS_DELIMITER, tag_name))

        index = bits.index(HTML_ATTRS_DELIMITER)
        html_bits = bits[index + 1:]
        bits = bits[:index]

        if not html_bits:
            raise template.TemplateSyntaxError('Don\'t use "%s" unless you\'re'
                ' setting html attributes.' % HTML_ATTRS_DELIMITER)

        args, html_attrs = parse_bits(parser, html_bits, [], 'args',
                'kwargs', None, [], None, False, tag_name)
        if len(args):
            raise template.TemplateSyntaxError('All "%s" tag arguments after'
                    ' the "%s" token must be named.' % (tag_name,
                    HTML_ATTRS_DELIMITER))

    return (tag_name, bits, html_attrs, varname)


@register.tag
def generateimage(parser, token):
    """
    Creates an image based on the provided arguments.

    By default::

        {% generateimage 'myapp:thumbnail' source=mymodel.profile_image %}

    generates an ``<img>`` tag::

        <img src="/path/to/34d944f200dd794bf1e6a7f37849f72b.jpg" width="100" height="100" />

    You can add additional attributes to the tag using "--". For example,
    this::

        {% generateimage 'myapp:thumbnail' source=mymodel.profile_image -- alt="Hello!" %}

    will result in the following markup::

        <img src="/path/to/34d944f200dd794bf1e6a7f37849f72b.jpg" width="100" height="100" alt="Hello!" />

    For more flexibility, ``generateimage`` also works as an assignment tag::

        {% generateimage 'myapp:thumbnail' source=mymodel.profile_image as th %}
        <img src="{{ th.url }}" width="{{ th.width }}" height="{{ th.height }}" />

    """
    bits = token.split_contents()

    tag_name, bits, html_attrs, varname = parse_ik_tag_bits(parser, bits)

    args, kwargs = parse_bits(parser, bits, ['generator_id'], 'args', 'kwargs',
            None, [], None, False, tag_name)

    if len(args) != 1:
        raise template.TemplateSyntaxError('The "%s" tag requires exactly one'
                ' unnamed argument (the generator id).' % tag_name)

    generator_id = args[0]

    if varname:
        return GenerateImageAssignmentNode(varname, generator_id, kwargs)
    else:
        return GenerateImageTagNode(generator_id, kwargs, html_attrs)


@register.tag
def thumbnail(parser, token):
    """
    A convenient shortcut syntax for generating a thumbnail. The following::

        {% thumbnail '100x100' mymodel.profile_image %}

    is equivalent to::

        {% generateimage 'imagekit:thumbnail' source=mymodel.profile_image width=100 height=100 %}

    The thumbnail tag supports the "--" and "as" bits for adding html
    attributes and assigning to a variable, respectively. It also accepts the
    kwargs "anchor", and "crop".

    To use "smart cropping" (the ``SmartResize`` processor)::

        {% thumbnail '100x100' mymodel.profile_image %}

    To crop, anchoring the image to the top right (the ``ResizeToFill``
    processor)::

        {% thumbnail '100x100' mymodel.profile_image anchor='tr' %}

    To resize without cropping (using the ``ResizeToFit`` processor)::

        {% thumbnail '100x100' mymodel.profile_image crop=0 %}

    """
    bits = token.split_contents()

    tag_name, bits, html_attrs, varname = parse_ik_tag_bits(parser, bits)

    args, kwargs = parse_bits(parser, bits, [], 'args', 'kwargs',
            None, [], None, False, tag_name)

    if len(args) < 2:
        raise template.TemplateSyntaxError('The "%s" tag requires at least two'
                ' unnamed arguments: the dimensions and the source image.'
                % tag_name)
    elif len(args) > 3:
        raise template.TemplateSyntaxError('The "%s" tag accepts at most three'
                ' unnamed arguments: a generator id, the dimensions, and the'
                ' source image.' % tag_name)

    dimensions, source = args[-2:]
    generator_id = args[0] if len(args) > 2 else None

    if varname:
        return ThumbnailAssignmentNode(varname, generator_id, dimensions,
                source, kwargs)
    else:
        return ThumbnailImageTagNode(generator_id, dimensions, source, kwargs,
                html_attrs)