Skip to content

Commit 9e6b792

Browse files
committed
Incomplete
1 parent abdd5c7 commit 9e6b792

File tree

2 files changed

+81
-65
lines changed

2 files changed

+81
-65
lines changed

webpack_loader/loaders.py

Lines changed: 41 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -91,26 +91,48 @@ def get_chunk_url(self, chunk_file):
9191
)
9292
return staticfiles_storage.url(relpath)
9393

94-
def get_bundle(self, bundle_name):
94+
def wait_for_assets(self):
9595
assets = self.get_assets()
9696

9797
# poll when debugging and block request until bundle is compiled
9898
# or the build times out
9999
if settings.DEBUG:
100100
timeout = self.config["TIMEOUT"] or 0
101-
timed_out = False
102101
start = time.time()
103-
while assets["status"] == "compile" and not timed_out:
102+
while assets["status"] == "compile":
104103
time.sleep(self.config["POLL_INTERVAL"])
105104
if timeout and (time.time() - timeout > start):
106-
timed_out = True
105+
raise WebpackLoaderTimeoutError(
106+
"Timed Out. Webpack took more than {0} "
107+
"seconds to compile.".format(self.config["TIMEOUT"] or 0)
108+
)
109+
107110
assets = self.get_assets()
108111

109-
if timed_out:
110-
raise WebpackLoaderTimeoutError(
111-
"Timed Out. Bundle `{0}` took more than {1} seconds "
112-
"to compile.".format(bundle_name, timeout)
113-
)
112+
return assets
113+
114+
def _process_assets_error(self, assets):
115+
if assets.get("status") == "error":
116+
if "file" not in assets:
117+
assets["file"] = ""
118+
if "error" not in assets:
119+
assets["error"] = "Unknown Error"
120+
if "message" not in assets:
121+
assets["message"] = ""
122+
error = """
123+
{error} in {file}
124+
{message}
125+
""".format(**assets)
126+
raise WebpackError(error)
127+
128+
raise WebpackLoaderBadStatsError(
129+
"The stats file does not contain valid data. Make sure "
130+
"webpack-bundle-tracker plugin is enabled and try to run "
131+
"webpack again."
132+
)
133+
134+
def get_bundle(self, bundle_name):
135+
assets = self.wait_for_assets()
114136

115137
if assets.get("status") == "done":
116138
chunks = assets["chunks"].get(bundle_name, None)
@@ -130,24 +152,17 @@ def get_bundle(self, bundle_name):
130152

131153
return self.map_chunk_files_to_url(filtered_chunks)
132154

133-
elif assets.get("status") == "error":
134-
if "file" not in assets:
135-
assets["file"] = ""
136-
if "error" not in assets:
137-
assets["error"] = "Unknown Error"
138-
if "message" not in assets:
139-
assets["message"] = ""
140-
error = """
141-
{error} in {file}
142-
{message}
143-
""".format(**assets)
144-
raise WebpackError(error)
155+
self._process_assets_error(assets)
145156

146-
raise WebpackLoaderBadStatsError(
147-
"The stats file does not contain valid data. Make sure "
148-
"webpack-bundle-tracker plugin is enabled and try to run "
149-
"webpack again."
150-
)
157+
def get_asset_url(self, asset_name):
158+
assets = self.wait_for_assets()
159+
try:
160+
asset_file = assets["assets"][asset_name]
161+
except KeyError:
162+
raise WebpackBundleLookupError(
163+
"Cannot resolve asset {0}.".format(asset_name)
164+
)
165+
return self.get_chunk_url(asset_file)
151166

152167

153168
class FakeWebpackLoader(WebpackLoader):

webpack_loader/utils.py

Lines changed: 40 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,24 @@
66

77

88
def import_string(dotted_path):
9-
'''
9+
"""
1010
This is a rough copy of django's import_string, which wasn't introduced until Django 1.7
1111
1212
Once this package's support for Django 1.6 has been removed, this can be safely replaced with
1313
`from django.utils.module_loading import import_string`
14-
'''
14+
"""
1515
try:
16-
module_path, class_name = dotted_path.rsplit('.', 1)
16+
module_path, class_name = dotted_path.rsplit(".", 1)
1717
module = import_module(module_path)
1818
return getattr(module, class_name)
1919
except (ValueError, AttributeError, ImportError):
20-
raise ImportError('%s doesn\'t look like a valid module path' % dotted_path)
20+
raise ImportError("%s doesn't look like a valid module path" % dotted_path)
2121

2222

2323
def get_loader(config_name):
2424
if config_name not in _loaders:
2525
config = load_config(config_name)
26-
loader_class = import_string(config['LOADER_CLASS'])
26+
loader_class = import_string(config["LOADER_CLASS"])
2727
_loaders[config_name] = loader_class(config_name, config)
2828
return _loaders[config_name]
2929

@@ -33,13 +33,13 @@ def get_skip_common_chunks(config_name):
3333
# The global default is currently False, whenever that is changed, change
3434
# this fallback value as well which is present to provide backwards
3535
# compatibility.
36-
return loader.config.get('SKIP_COMMON_CHUNKS', False)
36+
return loader.config.get("SKIP_COMMON_CHUNKS", False)
3737

3838

3939
def _filter_by_extension(bundle, extension):
40-
'''Return only files with the given extension'''
40+
"""Return only files with the given extension"""
4141
for chunk in bundle:
42-
if chunk['name'].endswith('.{0}'.format(extension)):
42+
if chunk["name"].endswith(".{0}".format(extension)):
4343
yield chunk
4444

4545

@@ -50,63 +50,64 @@ def _get_bundle(loader, bundle_name, extension):
5050
return bundle
5151

5252

53-
def get_files(bundle_name, extension=None, config='DEFAULT'):
54-
'''Returns list of chunks from named bundle'''
53+
def get_files(bundle_name, extension=None, config="DEFAULT"):
54+
"""Returns list of chunks from named bundle"""
5555
loader = get_loader(config)
5656
return list(_get_bundle(loader, bundle_name, extension))
5757

5858

59-
def get_as_tags(bundle_name, extension=None, config='DEFAULT', suffix='', attrs='', is_preload=False):
60-
'''
59+
def get_as_tags(
60+
bundle_name, extension=None, config="DEFAULT", suffix="", attrs="", is_preload=False
61+
):
62+
"""
6163
Get a list of formatted <script> & <link> tags for the assets in the
6264
named bundle.
6365
6466
:param bundle_name: The name of the bundle
6567
:param extension: (optional) filter by extension, eg. 'js' or 'css'
6668
:param config: (optional) the name of the configuration
6769
:return: a list of formatted tags as strings
68-
'''
70+
"""
6971

7072
loader = get_loader(config)
7173
bundle = _get_bundle(loader, bundle_name, extension)
7274
tags = []
7375

7476
for chunk in bundle:
75-
if chunk['name'].endswith(('.js', '.js.gz')):
77+
if chunk["name"].endswith((".js", ".js.gz")):
7678
if is_preload:
77-
tags.append((
78-
'<link rel="preload" as="script" href="{0}" {1}/>'
79-
).format(''.join([chunk['url'], suffix]), attrs))
79+
tags.append(
80+
('<link rel="preload" as="script" href="{0}" {1}/>').format(
81+
"".join([chunk["url"], suffix]), attrs
82+
)
83+
)
8084
else:
81-
tags.append((
82-
'<script src="{0}"{2}{1}></script>'
83-
).format(
84-
''.join([chunk['url'], suffix]),
85+
tags.append(
86+
('<script src="{0}"{2}{1}></script>').format(
87+
"".join([chunk["url"], suffix]),
88+
attrs,
89+
loader.get_integrity_attr(chunk),
90+
)
91+
)
92+
elif chunk["name"].endswith((".css", ".css.gz")):
93+
tags.append(
94+
('<link href="{0}" rel={2}{3}{1}/>').format(
95+
"".join([chunk["url"], suffix]),
8596
attrs,
97+
'"stylesheet"' if not is_preload else '"preload" as="style"',
8698
loader.get_integrity_attr(chunk),
87-
))
88-
elif chunk['name'].endswith(('.css', '.css.gz')):
89-
tags.append((
90-
'<link href="{0}" rel={2}{3}{1}/>'
91-
).format(
92-
''.join([chunk['url'], suffix]),
93-
attrs,
94-
'"stylesheet"' if not is_preload else '"preload" as="style"',
95-
loader.get_integrity_attr(chunk),
96-
))
99+
)
100+
)
97101
return tags
98102

99103

100-
def get_static(asset_name, config='DEFAULT'):
101-
'''
104+
def get_static(asset_name, config="DEFAULT"):
105+
"""
102106
Equivalent to Django's 'static' look up but for webpack assets.
103107
104108
:param asset_name: the name of the asset
105109
:param config: (optional) the name of the configuration
106110
:return: path to webpack asset as a string
107-
'''
108-
public_path = get_loader(config).get_assets().get('publicPath')
109-
if not public_path or public_path == 'auto':
110-
public_path = getattr(settings, 'STATIC_URL')
111-
112-
return '{0}{1}'.format(public_path, asset_name)
111+
"""
112+
loader = get_loader(config)
113+
return loader.get_asset_url(asset_name)

0 commit comments

Comments
 (0)