Skip to content

Instantly share code, notes, and snippets.

@tgecho
Created December 11, 2012 18:13
Show Gist options
  • Save tgecho/4260756 to your computer and use it in GitHub Desktop.
Save tgecho/4260756 to your computer and use it in GitHub Desktop.
LiveReload compatibility hack for Webassets
Tested with LiveReload 2.3.18
The only requirement is that the updating requests are sent with ?livereload={etc} in the url.
LiveReload should be configured to NOT compile the assets, as we want webassets to take care of this. We're
just using LR for the notification/loading parts.
import re
import os
from flask import current_app, redirect
def get_bundle_from_output(path, env_or_bundles):
for bundle in env_or_bundles:
output = getattr(bundle, 'output', None)
if output == path:
return bundle
elif output and '%(version)s' in output:
pattern = re.escape(output).replace('\%\(version\)s', '(\\w+)')
if re.match(pattern, path):
return bundle
if hasattr(bundle, 'contents'):
children = get_bundle_from_output(path, bundle.contents)
if children:
return children
# Example Flask handler
@app.before_request
def livereload():
if 'livereload' in request.args:
path = os.path.relpath(request.path, assets_env.url)
bundle = get_bundle_from_output(path, assets_env)
if bundle:
print 'Building', bundle
bundle.build(env=assets_env)
url = bundle.urls(env=assets_env)[0]
if url.split('?')[0] != request.path:
print 'Url changed, redirecting to', url
return redirect(url)
else:
print 'No bundle found for', path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment