File: forms.py

package info (click to toggle)
django-pipeline 4.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 904 kB
  • sloc: python: 3,170; makefile: 120; javascript: 59
file content (268 lines) | stat: -rw-r--r-- 9,287 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
"""Support for referencing Pipeline packages in forms and widgets."""

from django.contrib.staticfiles.storage import staticfiles_storage
from django.utils.functional import cached_property

from .collector import default_collector
from .conf import settings
from .packager import Packager


class PipelineFormMediaProperty:
    """A property that converts Pipeline packages to lists of files.

    This is used behind the scenes for any Media classes that subclass
    :py:class:`PipelineFormMedia`. When accessed, it converts any Pipeline
    packages into lists of media files and returns or forwards on lookups to
    that list.
    """

    def __init__(self, get_media_files_func, media_cls, extra_files):
        """Initialize the property.

        Args:
            get_media_files_func (callable):
                The function to call to generate the media files.

            media_cls (type):
                The Media class owning the property.

            extra_files (object):
                Files listed in the original ``css`` or ``js`` attribute on
                the Media class.
        """
        self._get_media_files_func = get_media_files_func
        self._media_cls = media_cls
        self._extra_files = extra_files

    @cached_property
    def _media_files(self):
        """The media files represented by the property."""
        return self._get_media_files_func(self._media_cls, self._extra_files)

    def __get__(self, *args, **kwargs):
        """Return the media files when accessed as an attribute.

        This is called when accessing the attribute directly through the
        Media class (for example, ``Media.css``). It returns the media files
        directly.

        Args:
            *args (tuple, unused):
                Unused positional arguments.

            **kwargs (dict, unused):
                Unused keyword arguments.

        Returns:
            object:
            The list or dictionary containing the media files definition.
        """
        return self._media_files

    def __getattr__(self, attr_name):
        """Return an attribute on the media files definition.

        This is called when accessing an attribute that doesn't otherwise
        exist in the property's dictionary. The call is forwarded onto the
        media files definition.

        Args:
            attr_name (unicode):
                The attribute name.

        Returns:
            object:
            The attribute value.

        Raises:
            AttributeError:
                An attribute with this name could not be found.
        """
        return getattr(self._media_files, attr_name)

    def __iter__(self):
        """Iterate through the media files definition.

        This is called when attempting to iterate over this property. It
        iterates over the media files definition instead.

        Yields:
            object:
            Each entry in the media files definition.
        """
        return iter(self._media_files)


class PipelineFormMediaMetaClass(type):
    """Metaclass for the PipelineFormMedia class.

    This is responsible for converting CSS/JavaScript packages defined in
    Pipeline into lists of files to include on a page. It handles access to the
    :py:attr:`css` and :py:attr:`js` attributes on the class, generating a
    list of files to return based on the Pipelined packages and individual
    files listed in the :py:attr:`css`/:py:attr:`css_packages` or
    :py:attr:`js`/:py:attr:`js_packages` attributes.
    """

    def __new__(cls, name, bases, attrs):
        """Construct the class.

        Args:
            name (bytes):
                The name of the class.

            bases (tuple):
                The base classes for the class.

            attrs (dict):
                The attributes going into the class.

        Returns:
            type:
            The new class.
        """
        new_class = super().__new__(cls, name, bases, attrs)

        # If we define any packages, we'll need to use our special
        # PipelineFormMediaProperty class. We use this instead of intercepting
        # in __getattribute__ because Django does not access them through
        # normal property access. Instead, grabs the Media class's __dict__
        # and accesses them from there. By using these special properties, we
        # can handle direct access (Media.css) and dictionary-based access
        # (Media.__dict__['css']).
        if "css_packages" in attrs:
            new_class.css = PipelineFormMediaProperty(
                cls._get_css_files, new_class, attrs.get("css") or {}
            )

        if "js_packages" in attrs:
            new_class.js = PipelineFormMediaProperty(
                cls._get_js_files, new_class, attrs.get("js") or []
            )

        return new_class

    def _get_css_files(cls, extra_files):
        """Return all CSS files from the Media class.

        Args:
            extra_files (dict):
                The contents of the Media class's original :py:attr:`css`
                attribute, if one was provided.

        Returns:
            dict:
            The CSS media types and files to return for the :py:attr:`css`
            attribute.
        """
        packager = Packager()
        css_packages = getattr(cls, "css_packages", {})

        return {
            media_target: cls._get_media_files(
                packager=packager,
                media_packages=media_packages,
                media_type="css",
                extra_files=extra_files.get(media_target, []),
            )
            for media_target, media_packages in css_packages.items()
        }

    def _get_js_files(cls, extra_files):
        """Return all JavaScript files from the Media class.

        Args:
            extra_files (list):
                The contents of the Media class's original :py:attr:`js`
                attribute, if one was provided.

        Returns:
            list:
            The JavaScript files to return for the :py:attr:`js` attribute.
        """
        return cls._get_media_files(
            packager=Packager(),
            media_packages=getattr(cls, "js_packages", {}),
            media_type="js",
            extra_files=extra_files,
        )

    def _get_media_files(cls, packager, media_packages, media_type, extra_files):
        """Return source or output media files for a list of packages.

        This will go through the media files belonging to the provided list
        of packages referenced in a Media class and return the output files
        (if Pipeline is enabled) or the source files (if not enabled).

        Args:
            packager (pipeline.packager.Packager):
                The packager responsible for media compilation for this type
                of package.

            media_packages (list of unicode):
                The list of media packages referenced in Media to compile or
                return.

            extra_files (list of unicode):
                The list of extra files to include in the result. This would
                be the list stored in the Media class's original :py:attr:`css`
                or :py:attr:`js` attributes.

        Returns:
            list:
            The list of media files for the given packages.
        """
        source_files = list(extra_files)

        if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED:
            default_collector.collect()

        for media_package in media_packages:
            package = packager.package_for(media_type, media_package)

            if settings.PIPELINE_ENABLED:
                source_files.append(staticfiles_storage.url(package.output_filename))
            else:
                source_files += packager.compile(package.paths)

        return source_files


class PipelineFormMedia(metaclass=PipelineFormMediaMetaClass):
    """Base class for form or widget Media classes that use Pipeline packages.

    Forms or widgets that need custom CSS or JavaScript media on a page can
    define a standard :py:class:`Media` class that subclasses this class,
    listing the CSS or JavaScript packages in :py:attr:`css_packages` and
    :py:attr:`js_packages` attributes. These are formatted the same as the
    standard :py:attr:`css` and :py:attr:`js` attributes, but reference
    Pipeline package names instead of individual source files.

    If Pipeline is enabled, these will expand to the output files for the
    packages. Otherwise, these will expand to the list of source files for the
    packages.

    Subclasses can also continue to define :py:attr:`css` and :py:attr:`js`
    attributes, which will be returned along with the other output/source
    files.

    Example:

        from django import forms
        from pipeline.forms import PipelineFormMedia


        class MyForm(forms.Media):
            ...

            class Media(PipelineFormMedia):
                css_packages = {
                    'all': ('my-form-styles-package',
                            'other-form-styles-package'),
                    'print': ('my-form-print-styles-package',),
                }

                js_packages = ('my-form-scripts-package',)
                js = ('some-file.js',)
    """