Material.init_app()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 64
rs 9.3956

1 Method

Rating   Name   Duplication   Size   Complexity  
A Material.lwrap() 0 2 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
#!/usr/bin/env python
2
# coding=utf8
3
4
__app_version__ = '0.1.1'
5
__material_version__ = '0.96.1'
6
7
import re
8
9
from flask import Blueprint, current_app, url_for
10
11
try:
12
    from wtforms.fields import HiddenField
13
except ImportError:
14
    def is_hidden_field_filter(field):
15
        raise RuntimeError('WTForms is not installed.')
16
else:
17
    def is_hidden_field_filter(field):
18
        return isinstance(field, HiddenField)
19
20
21
class CDN(object):
22
    """Base class for CDN objects."""
23
    def get_resource_url(self, filename):
24
        """Return resource url for filename."""
25
        raise NotImplementedError
26
27
28
class StaticCDN(object):
29
    """A CDN that serves content from the local application.
30
31
    :param static_endpoint: Endpoint to use.
32
    :param rev: If ``True``, honor ``MATERIAL_QUERYSTRING_REVVING``.
33
    """
34
    def __init__(self, static_endpoint='static', rev=False):
35
        self.static_endpoint = static_endpoint
36
        self.rev = rev
37
38
    def get_resource_url(self, filename):
39
        extra_args = {}
40
41
        if self.rev and current_app.config['MATERIAL_QUERYSTRING_REVVING']:
42
            extra_args['material'] = __version__
43
44
        return url_for(self.static_endpoint, filename=filename, **extra_args)
45
46
47
class WebCDN(object):
48
    """Serves files from the Web.
49
50
    :param baseurl: The baseurl. Filenames are simply appended to this URL.
51
    """
52
    def __init__(self, baseurl):
53
        self.baseurl = baseurl
54
55
    def get_resource_url(self, filename):
56
        return self.baseurl + filename
57
58
59
class ConditionalCDN(object):
60
    """Serves files from one CDN or another, depending on whether a
61
    configuration value is set.
62
63
    :param confvar: Configuration variable to use.
64
    :param primary: CDN to use if the configuration variable is ``True``.
65
    :param fallback: CDN to use otherwise.
66
    """
67
    def __init__(self, confvar, primary, fallback):
68
        self.confvar = confvar
69
        self.primary = primary
70
        self.fallback = fallback
71
72
    def get_resource_url(self, filename):
73
        if current_app.config[self.confvar]:
74
            return self.primary.get_resource_url(filename)
75
        return self.fallback.get_resource_url(filename)
76
77
78
def material_find_resource(filename, cdn, use_minified=None, local=True):
79
    """Resource finding function, also available in templates.
80
81
    Tries to find a resource, will force SSL depending on
82
    ``MATERIAL_CDN_FORCE_SSL`` settings.
83
84
    :param filename: File to find a URL for.
85
    :param cdn: Name of the CDN to use.
86
    :param use_minified': If set to ``True``/``False``, use/don't use
87
                          minified. If ``None``, honors
88
                          ``MATERIAL_USE_MINIFIED``.
89
    :param local: If ``True``, uses the ``local``-CDN when
90
                  ``MATERIAL_SERVE_LOCAL`` is enabled. If ``False``, uses
91
                  the ``static``-CDN instead.
92
    :return: A URL.
93
    """
94
    config = current_app.config
95
96
    if config['MATERIAL_SERVE_LOCAL']:
97
        if 'css/' not in filename and 'js/' not in filename:
98
            filename = 'js/' + filename
99
100
    if None == use_minified:
101
        use_minified = config['MATERIAL_USE_MINIFIED']
102
103
    if use_minified:
104
        filename = '%s.min.%s' % tuple(filename.rsplit('.', 1))
105
106
    cdns = current_app.extensions['material']['cdns']
107
    resource_url = cdns[cdn].get_resource_url(filename)
108
109
    if resource_url.startswith('//') and config['MATERIAL_CDN_FORCE_SSL']:
110
        resource_url = 'https:%s' % resource_url
111
112
    return resource_url
113
114
115
class Material(object):
116
    def __init__(self, app=None):
117
        if app is not None:
118
            self.init_app(app)
119
120
    def init_app(self, app):
121
        MATERIAL_VERSION = '0.96.1'
122
        JQUERY_VERSION = '1.11.3'
123
        HTML5SHIV_VERSION = '3.7.2'
124
        RESPONDJS_VERSION = '1.4.2'
125
126
        app.config.setdefault('MATERIAL_USE_MINIFIED', True)
127
        app.config.setdefault('MATERIAL_CDN_FORCE_SSL', False)
128
129
        app.config.setdefault('MATERIAL_QUERYSTRING_REVVING', True)
130
        app.config.setdefault('MATERIAL_SERVE_LOCAL', False)
131
132
        app.config.setdefault('MATERIAL_LOCAL_SUBDOMAIN', None)
133
134
        blueprint = Blueprint(
135
            'material',
136
            __name__,
137
            template_folder='templates',
138
            static_folder='static',
139
            static_url_path=app.static_url_path + '/material',
140
            subdomain=app.config['MATERIAL_LOCAL_SUBDOMAIN'])
141
142
        app.register_blueprint(blueprint)
143
144
        app.jinja_env.globals['material_is_hidden_field'] =\
145
            is_hidden_field_filter
146
        app.jinja_env.globals['material_find_resource'] =\
147
            material_find_resource
148
149
        if not hasattr(app, 'extensions'):
150
            app.extensions = {}
151
152
        local = StaticCDN('material.static', rev=True)
153
        static = StaticCDN()
154
155
        def lwrap(cdn, primary=static):
156
            return ConditionalCDN('MATERIAL_SERVE_LOCAL', primary, cdn)
157
158
        material = lwrap(
159
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/materialize/%s/'
160
                   % MATERIAL_VERSION),
161
            local)
162
163
        jquery = lwrap(
164
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/%s/'
165
                   % JQUERY_VERSION),
166
            local)
167
168
        html5shiv = lwrap(
169
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/html5shiv/%s/'
170
                   % HTML5SHIV_VERSION))
171
172
        respondjs = lwrap(
173
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/respond.js/%s/'
174
                   % RESPONDJS_VERSION))
175
176
        app.extensions['material'] = {
177
            'cdns': {
178
                'local': local,
179
                'static': static,
180
                'material': material,
181
                'jquery': jquery,
182
                'html5shiv': html5shiv,
183
                'respond.js': respondjs,
184
            },
185
        }
186