Integrates the webassets library with Flask, adding support for merging, minifying and compiling CSS and Javascript files.
- Documentation:
- https://flask-assets.readthedocs.io/
Flask webassets integration.
License: BSD 2-Clause "Simplified" License
Integrates the webassets library with Flask, adding support for merging, minifying and compiling CSS and Javascript files.
i have flask application with buildout in src folder
Version: 0.10.1
Version: 0.10
src/setup.py have following strings
setup( name = 'spf', install_requires = [ 'flask', 'flask-assets', ], entry_points = { 'console_scripts': [ 'spf_dev = spf.manage:dev', /* see manage.py dev function */ ], }, }
src/spf/manage.py
from flask.ext import assets from . import env def init (app): manager = script.Manager(app) manager.add_command( 'assets', assets.ManageAssets(app.assets), ) return manager def dev (): init(env.dev.app).run()
src/spf/env/dev.py
from spf import init app = init({ 'ASSETS_DIR': 'src/spf/static/assets', 'ASSETS_URL': '/assets/', 'SASS_STYLE': 'compressed', 'UGLIFYJS_EXTRA_ARGS': ( '-c', '--screw-ie8', ), })
src/spf/init.py
import flask from . import assets def init (env_config=None): app = flask.Flask( 'spf', static_url_path='', ) app.config.update(evn_config) app.assets = assets.Assets(app) return app
src/spf/assets.py
from flask.ext.assets import ( Environment, Bundle, ) class Assets (Environment): def __init__ (self, app): super(Assets, self).__init__(app) if 'ASSETS_DIR' in app.config: self.directory = app.config['ASSETS_DIR'] if 'ASSETS_URL' in app.config: self.url = app.config['ASSETS_URL'] if 'SASS_STYLE' in app.config: self.config['sass_style'] = app.config['SASS_STYLE'] if 'UGLIFYJS_EXTRA_ARGS' in app.config: self.config['UGLIFYJS_EXTRA_ARGS'] = \ app.config['UGLIFYJS_EXTRA_ARGS'] self.register('theme.css', Bundle( 'scss/theme.scss', filters='scss', output='theme.css', )) self.append_path('src/assets')
src/assets/scss/theme.scss
@import 'btn-o';
src/assets/scss/_btn-o.scss exists and have 0777 access right
but when i run
./bin/spf_dev assets -v build
i have error
Building bundle: theme.css Failed, error was: sass: subprocess had error: stderr=Error: File to import not found or unreadable: ./btn-o. on line 1 of standard input Use --trace for backtrace. , stdout=, returncode=65
i have read https://github.com/miracle2k/webassets/blob/master/src/webassets/filter/sass.py#L36
but i don't understand
why sass don't use src/assets for resolve relative path in @import directive from stdin?
self.append_path('src/assets')
(venv)[myapp] ./manage.py assets --parse-templates build
Searching templates...
Traceback (most recent call last):
File "./manage.py", line 61, in <module>
manager.run()
File "/Users/philfreo/Sites/_es/myapp/venv/lib/python2.7/site-packages/flaskext/script.py", line 710, in run
self.handle(sys.argv[0], command, sys.argv[2:])
File "/Users/philfreo/Sites/_es/myapp/venv/lib/python2.7/site-packages/flaskext/script.py", line 682, in handle
command.handle(app, *positional_args, **command_namespace.__dict__)
File "/Users/philfreo/Sites/_es/myapp/venv/lib/python2.7/site-packages/flaskext/script.py", line 193, in handle
self.run(*args, **kwargs)
File "/Users/philfreo/Sites/_es/myapp/venv/src/flask-assets/src/flask_assets.py", line 345, in run
impl.main(args)
File "/Users/philfreo/Sites/_es/myapp/venv/src/webassets/src/webassets/script.py", line 555, in main
return self.run_with_argv(argv)
File "/Users/philfreo/Sites/_es/myapp/venv/src/webassets/src/webassets/script.py", line 547, in run_with_argv
return self.run_with_ns(ns)
File "/Users/philfreo/Sites/_es/myapp/venv/src/webassets/src/webassets/script.py", line 529, in run_with_ns
env = self._setup_assets_env(ns, log)
File "/Users/philfreo/Sites/_es/myapp/venv/src/flask-assets/src/flask_assets.py", line 287, in _setup_assets_env
env.add(*[b for b in self.load_from_templates(env)
File "/Users/philfreo/Sites/_es/myapp/venv/src/flask-assets/src/flask_assets.py", line 309, in load_from_templates
path.join(blueprint.root_path, blueprint.template_folder))
AttributeError: 'str' object has no attribute 'root_path'
Looks like blueprint
is a string for all the blueprints in app.blueprints
. Did I setup something wrong or is this a bug?
The docs say that these are equivalent.
assets_env.debug = True
app.config['ASSETS_DEBUG'] = True
When I try this
assets_env = Environment()
assets_env.debug = True
assets_env.init_app(app)
I get RuntimeError: assets instance not bound to an application, and no application in current context
.
However this works.
assets_env = Environment()
app.config['ASSETS_DEBUG'] = True
assets_env.init_app(app)
It would be good if the docs had a warning about this.
I am getting the following error when I try to build assets using the --parse-templates
option. Im not really sure where to start debugging this...
Searching templates...
Traceback (most recent call last):
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/jinja2/nodes.py", line 386, in as_const
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/jinja2/nodes.py", line 365, in as_const
raise Impossible()
jinja2.nodes.Impossible
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/jinja2/nodes.py", line 386, in as_const
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/jinja2/nodes.py", line 388, in as_const
raise Impossible()
jinja2.nodes.Impossible
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 110, in <module>
manager.run()
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/flask_script/__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/flask_script/__init__.py", line 383, in handle
res = handle(*args, **config)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/flask_script/commands.py", line 216, in __call__
return self.run(*args, **kwargs)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/flask_assets.py", line 422, in run
return impl.main(args)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/script.py", line 557, in main
return self.run_with_argv(argv)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/script.py", line 549, in run_with_argv
return self.run_with_ns(ns)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/script.py", line 531, in run_with_ns
env = self._setup_assets_env(ns, log)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/flask_assets.py", line 364, in _setup_assets_env
env.add(*[b for b in self.load_from_templates(env, ns.jinja_extension)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/flask_assets.py", line 391, in load_from_templates
load_bundles()
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/ext/jinja2.py", line 218, in load_bundles
bundles.extend(self.with_file(filename, self._parse) or [])
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/loaders.py", line 301, in with_file
return then_run(filename, contents)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/ext/jinja2.py", line 246, in _parse
_recurse_node(node)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/ext/jinja2.py", line 244, in _recurse_node
_recurse_node(node)
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/webassets/ext/jinja2.py", line 237, in _recurse_node
*AssetsExtension.resolve_contents(files.as_const(), self.asset_env),
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/jinja2/nodes.py", line 490, in as_const
return [x.as_const(eval_ctx) for x in self.items]
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/jinja2/nodes.py", line 490, in <listcomp>
return [x.as_const(eval_ctx) for x in self.items]
File "/Users/joe/Sites/_projects/words/venv3/lib/python3.4/site-packages/jinja2/nodes.py", line 388, in as_const
raise Impossible()
jinja2.nodes.Impossible
Allo,
app.config['ASSETS_DEBUG']
{% assets filters="cssmin", output="css/gen/style.css",
"css/bootstrap.css", "css/bootstrap-responsive.css", "css/custom.css" -%}
<link href="{{ ASSET_URL }}" rel="stylesheet">
{%- endassets %}
{% assets filters="cssutils", output="css/gen/style.css",
"css/bootstrap.css", "css/bootstrap-responsive.css", "css/custom.css" -%}
<link href="{{ ASSET_URL }}" rel="stylesheet">
{%- endassets %}
<head>
<link href="/static/css/bootstrap.css" rel="stylesheet">
<link href="/static/css/bootstrap-responsive.css" rel="stylesheet">
<link href="/static/css/custom.css" rel="stylesheet">
<link href="/static/css/gen/style.css?f54629cf" rel="stylesheet">
</head>
As far as I can see the Flask-Script 0.6 is not supported. Running command results in
Traceback (most recent call last):
File "manage.py", line 15, in <module>
manager.run()
File "/blah/blah/blah/python2.7/site-packages/flask_script/__init__.py", line 366, in run
raise e
TypeError: create_parser() got an unexpected keyword argument 'parents'
I am setting config variables for Flask-Asset's in the documentation, for example
# Flask-Assets / webassets
ASSETS_DEBUG = True
ASSETS_UGLIFYJS_EXTRA_ARGS = ['-nc']
I am initializing the assets environment in an application factory:
assets = Environment()
def create_app(config=None):
app = Flask(__name__)
if config is not None:
app.config.from_object(config)
db.init_app(app)
assets.init_app(app)
While the DEBUG option works fine.. the extra args for uglifyjs do not get passed. Perhaps I am doing something wrong? Are all Flask config options prepended with ASSETS_ parsed?
Thanks again for webassets + Flask-Assets. Truly invaluable.
It breaks cssrewrite filter, because my blueprint has a url_prefix
with a <param>
and url_for
needs the url_defaults
to build the URL.
For the past three months I've been running my production off git because of a bug in webassets 0.9. This seems fixed now but the flask-assets dependency is preventing me from using it - is there a significant showstopper from releasing a version of flask-assets that supports 0.10 webassets?
Hi,
Would you be interested in having support for bower integrated into Flask-Assets or Webassets? What we have in mind is being able to specify bower dependencies in Bundles, e.g.:
css = Bundle(
'less/styles.less',
filters='less, cleancss',
output='gen/styles.%(version)s.css',
bower={
"bootstrap": "~3.3.5",
}
)
Then have a CLI command similar to below to collect bower requirements from all bundles in an environment in order to generate a bower.json
:
$ manage.py bower
{
"name": "",
"dependencies": {
"bootstrap": "~3.3.5",
}
}
A typical use would be like below (generate bower.json
, run bower install, then build assets):
$ manage.py bower --output-file bower.json
$ bower install
$ manage.py assets build
The difference from just writing a bower.json
in your text editor is that it allows an application to integrate external bundles without having to worry about which assets you need to download (e.g. collecting bower requirements from all applications in INSTALLED_APPS
in a Django).
If it has any interest, we'll be happy to create a PR, otherwise just close the issue.
Cheers,
Lars
For retrieving assets in production.
$ pip install Flask-Assets -v
Downloading/unpacking Flask-Assets
Using version 0.7 (newest of versions: 0.7, 0.6.2, 0.6.1, 0.6, 0.5.1, 0.2.2, 0.2.1, 0.2, 0.1)
$ pip install "Flask-Assets==0.8" --upgrade
Downloading/unpacking Flask-Assets==0.8
Could not find a version that satisfies the requirement Flask-Assets==0.8 (from versions: )
I'm fairly new to python so I can't seem to figure out why this is not working properly, but it's really anoying because version 0.7 still uses from flaskext import script
but Flask-Script has long moved on to only supporting from flask.ext import script
so now I'm stuck with an old version of Flask-Script too!
Just running tox to test another application, and this is the tail end of the error:
File "/.../.tox/py33/lib/python3.3/site-packages/flask_assets.py", line 5, in <module>
from webassets.env import ( File "/..../.tox/py33/lib/python3.3/site-packages/webassets/__init__.py", line 5, in <module>
from bundle import Bundle
ImportError: No module named 'bundle'
I have other packages in my environment having a requirement for the webassets package. These upgrade webassets to 0.9. And then while running pip installs with the --upgrade flag, I face an error which says:
error: Installed distribution webassets 0.9 conflicts with requirement webassets==0.8
On deeper probe, I figured it is flask-assets which has a specified dependency on webassets==0.8.
vagrant@dev:/usr/local/lib/python2.7/dist-packages$ sudo grep -r ==0.8 *
Flask_Assets-0.8-py2.7.egg/EGG-INFO/requires.txt:webassets==0.8
Any particular problem that holds flask-assets back from supporting webassets latest version?
Hello there Michael, hope you're doing well 😄
It seems that the assets management command extension for Flask-Script fails to work on most versions of Python.
Here's my test script:
#!/usr/bin/env python
from flask import Flask
from flask.ext.script import Manager
from flask.ext.assets import Environment, Bundle, ManageAssets
app = Flask(__name__)
assets_env = Environment(app)
js = Bundle('jquery.js', 'base.js', 'widgets.js',
filters='jsmin', output='gen/packed.js')
assets_env.register('js_all', js)
manager = Manager(app)
manager.add_command("assets", ManageAssets(assets_env))
if __name__ == '__main__':
manager.run()
For each example below, I created a virtualenv using the version of Python mentioned and then installed the following:
pip install Flask-Script Flask-Assets
Python 2.6.9: This doesn't allow me to use sub-options at all I'm afraid
(scripts-2.6.9)fots@fotsies-ubprecise-01:~/flask-assets-test$ python -V
Python 2.6.9
(scripts-2.6.9)fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets
usage: testit.py assets [-h] [-v] [-q] [--parse-templates]
{watch,build,clean,check} ...
testit.py assets: error: too few arguments
(scripts-2.6.9)fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets check
usage: testit.py assets [-h]
testit.py assets: error: unrecognized arguments: check
Python 2.7.6: This works as expected
(scripts-2.7.6)fots@fotsies-ubprecise-01:~/flask-assets-test$ python -V
Python 2.7.6
(scripts-2.7.6)fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets
usage: testit.py assets [-h] [-v] [-q] [--parse-templates]
{watch,build,clean,check} ...
testit.py assets: error: too few arguments
(scripts-2.7.6)fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets check
Checking asset: gen/packed.js
needs update
Python 3.3.5: Fails to list command help, but seems to respond to sub-options
(scripts-3.3.5) fots@fotsies-ubprecise-01:~/flask-assets-test$ python -V
Python 3.3.5
(scripts-3.3.5) fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets
unknown command: None
(scripts-3.3.5) fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets check
Checking asset: gen/packed.js
needs update
Python 3.4.0: Same as Python 3.3.5 above
(scripts-3.4) fots@fotsies-ubprecise-01:~/flask-assets-test$ python -V
Python 3.4.0
(scripts-3.4) fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets
unknown command: None
(scripts-3.4) fots@fotsies-ubprecise-01:~/flask-assets-test$ ./testit.py assets check
Checking asset: gen/packed.js
needs update
Any help would be greatly appreciated! 😄
Cheers
Fotis
How do i gzip the assets created with flask assets.
I tried everything, but if i choose pyScss as filter it just doesn't work. Keep getting "KeyError" on scss.STATIC_URL = self.env.url
I have a deploy procedure where i want to compile the static assets locally, commit them to the repo and then don't compile in production. This way the server does not need any extra packages like node, yahoo compile etc.
Also this will not stall the initial request by compiling the assets. Is there any plan for an option like this or should i work on that.
I've been able to use flask-assets to bundle my css and js and serve using a versioned path. I also need to serve images using a versioned path, can webassets and flask-assets help me render images in my templates on versioned paths?
For some reason the def _app
is returning nothing, but if set self.app
in init_app
ist works.
The Function init_app
should look like this:
def init_app(self, app):
self.app = app
app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
app.jinja_env.assets_environment = self
I just want to merge js files but not compress it. How do i do it.
This is what happens when I run the test suite.
$ python2.7 setup.py test
running test
running egg_info
writing requirements to src/Flask_Assets.egg-info/requires.txt
writing src/Flask_Assets.egg-info/PKG-INFO
writing top-level names to src/Flask_Assets.egg-info/top_level.txt
writing dependency_links to src/Flask_Assets.egg-info/dependency_links.txt
reading manifest file 'src/Flask_Assets.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
no previously-included directories found matching 'docs/_build'
no previously-included directories found matching 'docs/_themes/.git'
warning: no previously-included files matching '*.pyc' found under directory 'example'
writing manifest file 'src/Flask_Assets.egg-info/SOURCES.txt'
running build_ext
tests.test_config.TestConfigAppBound.test_custom_values
Custom config values are relayed to the Flask config as.is. ... ok
tests.test_config.TestConfigAppBound.test_no_override
Ensure that the webassets defaults do not override existing ... ok
tests.test_config.TestConfigAppBound.test_set_config
Setting a value in the Flask config works. ... ok
tests.test_config.TestConfigAppBound.test_set_environment
Setting a config value on the environment works. ... ok
tests.test_config.TestConfigNoAppBound.test_global_defaults
We may set defaults even without an application, however. ... ok
tests.test_config.TestConfigNoAppBound.test_key_error
KeyError is raised if a config value doesn't exist. ... ok
tests.test_config.TestConfigNoAppBound.test_multiple_separate_apps
Each app has it's own separate configuration. ... ok
tests.test_config.TestConfigNoAppBound.test_no_app_available
Without an application bound, we can't do much. ... ok
tests.test_env.TestEnv.test_from_python_module
Python configuration module gets loaded ... ok
tests.test_env.TestEnv.test_from_yaml
YAML configuration gets loaded ... ok
tests.test_env.TestEnv.test_tag_available
Jinja tag has been made available. ... ok
tests.test_integration.TestBlueprints.test_blueprint_no_static_folder
Test dealing with a blueprint without a static folder. ... ok
tests.test_integration.TestBlueprints.test_blueprint_output
[Regression] Output can point to a blueprint's static ... ok
tests.test_integration.TestBlueprints.test_blueprint_urls
Urls to blueprint files are generated correctly. ... ok
tests.test_integration.TestBlueprints.test_cssrewrite
Make sure cssrewrite works with Blueprints. ... ok
tests.test_integration.TestBuild.test_build ... ok
tests.test_integration.TestBuild.test_with_cache_default_directory
[Regression] The cache directory is created in the Flask ... ok
tests.test_integration.TestUrlAndDirectory.test_config_values_not_set_by_default ... ok
tests.test_integration.TestUrlAndDirectory.test_custom_directory_and_url
Custom directory/url are configured - this will affect how ... ok
tests.test_integration.TestUrlAndDirectory.test_custom_load_path
A custom load_path is configured - this will affect how ... ok
tests.test_integration.TestUrlAndDirectory.test_directory_auto
Test how we resolve file references through the Flask static ... ok
tests.test_integration.TestUrlAndDirectory.test_existing_request_object_used
[Regression] Check for a bug where the url generation code of ... ok
tests.test_integration.TestUrlAndDirectory.test_glob
Make sure url generation works with globs. ... ok
tests.test_integration.TestUrlAndDirectory.test_url_auto
Test how urls are generated via the Flask static system ... ok
tests.test_integration.TestUrlAndDirectoryWithInitApp.test
Make sure the "url" and "directory" config values are ... ok
tests.test_integration.test_import ... ok
tests.test_script.TestScript.test_call ... ERROR
tests.test_script.TestScript.test_call_auto_env
Regression test: Passing the environment to the ManageAssets command ... ok
tests.test_script.TestScript.test_parse_templates
Test the --parse-templates option. ... ok
======================================================================
ERROR: tests.test_script.TestScript.test_call
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/home/edward/src/deb_dist/flask-assets-0.11/tests/test_script.py", line 52, in test_call
assert self.last_script_call == ['-h']
AttributeError: 'TestScript' object has no attribute 'last_script_call'
-------------------- >> begin captured stdout << ---------------------
usage: manage.py assets [-h]
Manage assets.
optional arguments:
-h, --help show this help message and exit
--------------------- >> end captured stdout << ----------------------
----------------------------------------------------------------------
Ran 29 tests in 0.201s
FAILED (errors=1)
$
I would like to use flask-assets to organize my webassets and mako for templating. Flask-assets normally uses jinja in the following way:
{% assets "js_all" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
The Mako equivalent (as far as I know) would be the following:
% assets 'coffee':
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
% endassets
However this causes a compile error:
mako.exceptions.CompileException
CompileException: Unsupported control keyword: 'assets' in file '/index.html' at line: 8 char: 1
Is there any way to use custom control keywords (like 'assets') in Mako, or set up Flask-Assets to interact with Mako?
Is there a way I can add assets to a bundle within a route?
the standard way of render url takes 3 lines
{% assets 'main_css' %}
<link rel="stylesheet" href="{{ASSET_URL}}">
{% endassets %}
This seems to be a bit verbose
I am wondering if it's possible to provide helper function in template like this:
<link rel="stylesheet" href="{{asset_url('main_css')}}">
If you setup your Flask installation as describe here: http://flask.pocoo.org/docs/patterns/packages/#modules-and-resources, flask-assets isn't able to find static files stored in the module's static directory.
I'm deploying my Flask app in a location that requires a prefix in the URL and I'm using a middleware to prepend the prefix to the WSGI's SCRIPT_NAME. When this is used in combination with Flask-Assets, the resulting URLs for assets are incorrect, as they are not processed within the same request context and they lack the prefix.
For reference on the issue, see the Flask mailing list thread.
I want to use a packed assets file, but I never want it automatically updated because I'm updating it manually (by rendering the template once with assets.update = 'always').
The problem is that I can't seem to run flask-assets with both:
assets.debug = False
assets.updater = False
I get the error (even though the packed file exists):
BuildError: ... needs to be created, but automatic building is disabled (configure an updater)
I might be doing something dumb... but I can't figure it out.
BTW: I'm using google app engine
Attempting to use the following pattern, then setting config values, like so...:
app = Flask(__name__)
assets = flask.ext.assets.Environment() # note no app being passed via constructor
assets.init_app(app) # initializing assets via init_app() here...
assets.cache = False # <--- ERROR!
assets.debug = True # <--- ERROR!
…results in errors (marked above) RuntimeError: assets instance not bound to an application, and no application in current context
.
Examining further, it seems that the init_app()
method does not set self.app
, causing the _app
property to throw the exception when subsequent attempts to use the ostensibly "init'd app" via init_app()
.
Current Code (~line 328 in flask_assets.py):
def init_app(self, app):
app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
app.jinja_env.assets_environment = self
Proposed Solution - add single line…:
def init_app(self, app):
self.app = app # <--- setting the self.app to satisfy `._app` property!
app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
app.jinja_env.assets_environment = self
Heya, I'm using flask-assets and find it quite awesome. One of the things I find lacking, however, is a filter that simply processes a file through Jinja2.
webassets doesn't include this at all, which makes it difficult to write purely CSS-driven sites. For instance, I often find myself writing HTML minimally, and specifying all image paths in my CSS files, eg:
body {
background: url({{ config.STATIC_URL }}/img/background.png);
}
This allows me to easily control the style of my site without actually touching the template layer. Also: I can serve static files locally in development, while serving them from something like S3 in production.
Anyhow, in order for me to do the above, I have to process my template with a custom webasset filter that uses Flask's render_template_string
function (so that I get all the standard Flask contexts: url_for
, config
, g
, etc.).
What I'm wondering is this: if I submit a pull request which contains my custom Jinja2 filter for use with webassets, would you consider accepting it? I thought about submitting it to the webassets
project itself, but after thinking about it, I think it would be difficult to get accepted there since this filter is only useful when paired with the standard Flask contexts.
Anyhow, let me know! If you'd like me to, I'd be happy to submit a pull request with the filter, it's very simple.
Hey everyone,
I'm having an issue trying to use pyScss
instead of the external sass
filter. When I switch over to pyScss
I get the following error:
File "/path/to/project/.env/lib/python2.7/site-packages/webassets/filter/pyscss.py", line 97, in setup
scss.config.STATIC_ROOT = self.static_root or self.env.directory
AttributeError: 'module' object has no attribute 'config'
Here's the code I'm using to set up the environment:
app = Flask(__name__)
app.config["ASSETS_DEBUG"] = True
assets = Environment(app)
assets.url = app.static_url_path
scss = Bundle("stylesheets/main.scss",
filters="pyscss",
output="all.css",
depends="stylesheets/partials/*.scss")
assets.register("style", scss)
Nothing too complicated/fancy and it worked a-okay when pyscss
was replaced with sass
. I'm a bit confused as to what could be going wrong here. Any thoughts?
Thanks in advance!
I would love to use flask-assets CDN integration, but the current release (0.10) does not have it.
Thanks for a great library.
Hi, i don't know if its realy a flask-assets bug but it appears when using it.
All my web projects on the server worked with flask-assets fine, since some time. All projects at the same time broked.
From all projects i got: ImportError: No module named flask.ext.assets
When i activate the env (all projects are installed in virtualenvs) and do the same import, it will work.
So i don't know if its realy a flask-assts problem but i hope you can help me.
$ pip freeze
Flask==0.10.1
Flask-Assets==0.8
Flask-Mail==0.9.0
Flask-WTF==0.9.1
Jinja2==2.7.1
MarkupSafe==0.18
WTForms==1.0.4
Werkzeug==0.9.4
blinker==1.3
cssmin==0.1.4
distribute==0.7.3
itsdangerous==0.23
webassets==0.8
wsgiref==0.1.2
See https://github.com/sean-lynch/flask-assets-issues/blob/master/1/app.py for an example
If an environment has both assets.updater = 'always' and assets.cache = False, the JST file generated breaks itself after the second time the page is loaded. In the example, the first time the bundle is generated, the result is:
window.JST = window.JST || {};
var template = function(str){/* ... common JST code ... */};
window.JST['template'] = template('
When the page is refreshed and the bundle is generated a second time, it becomes:
window.JST = window.JST || {};
var template = function(str){/* ... common JST code ... */};
window.JST[''] = template('
Couldn't replicate this using webassets directly.
How to use spritemapper filter.
Maybe an example of usage of all builtins filters are welcome.
When using a https proxy, such as Elastic Load Balancer, when configured to proxy https to http (middleman ssl) the flask application does not see the scheme as https. The simplest solution for this would be to render assets without a scheme, simply using //domain/public/asset.css
At the bottom of this documentation it discusses a number of topics I am interested in, but none of the italicised text are links, so I can't figure out how to get there.
Currently the latest stable release is not compatible with how Flask handles the exception, see this commit: 006864b.
So we can’t use ManageAsset() with Flask-Script for example.
The fix is already present in master, when will you push the next major version?
I am using the less and it works beautifully. Now how do i minify the css.
{% assets filters="less", output="gen/packed.css", "less/bootstrap.less" %}
<link href="{{ ASSET_URL }}" rel="stylesheet">
{% endassets %}
less supports -x option. how do i specify it. If not how do i specify multiple filters.
Second where do i mention this
if env.debug:
js_bundle.contents += 'http://lesscss.googlecode.com/files/less-1.3.0.min.js'
and this
env.config['less_run_in_debug'] = False
Hi,
I get KeyError exceptions with 0.6, complaining about missing directory
key. The following code works with 0.5.1, but not with 0.6:
The cssrewrite
filter doesn't work as expected with bundles exposed by a blueprint.
If a blueprint at /blueprint
exposes css/blue.css
as a static file, the Flask URL is /blueprint/css/blue.css
. If this file is integrated into the app's static folder with cssrewrite
, becoming /static/css/app.css
, URLs aren't rewritten with ../../blueprint/css
. They instead get ../blueprint/static/css
, reflecting the actual path on disk.
Since Flask-Assets and webassets are capable of resolving paths to blueprints, this appears to be an oversight in the cssrewrite
filter.
I have a bundle defined like this:
bootstrap_js = Bundle(
"libs/bootstrap/js/*.js"
)
Since a few days ago (I guess with the new release) the glob is not working, instead of having multiple URLs I get one to "http://localhost:8080/static/libs/bootstrap/js/*.js"
After a quick look in the source code I didn't find an easy fix, but I think it's got something to do with the method FlaskResolver.resolve_source_to_url.
Also, I did a git bisect and it told me the first bad commit is 3d9913f
I'd be happy to provide more info if you want.
I'm running Management Command (http://flask-assets.readthedocs.org/en/latest/index.html#management-command) to pre-build the bundle (I'm using GAE).
It works very well for bunble declared in code
bundle = Bundle('js/main.js', 'js/lib/bootstrap-2.0.3.min.js', filters="jsmin", output="gen/test.js")
assets_env.register('test', bundle)
But it doesn't seems to work with bundle declared in Template (couldn't detect this bundle)
{% assets filter="cssmin", output="gen/test.css",
"css/bootstrap-2.0.2.css", "css/bootstrap-responsive-2.0.2.css", "css/test.css" %}
{% endassets %}
Is template bundle detection working? Or am I missing some configurations?
#36 fixes the broken globbing funtionality, could you release this fix to pypi?
This would be useful for assets that are small when compressed.
The flask-script "clean" command fails with:
Cleaning generated assets...
Traceback (most recent call last):
File "manage.py", line 29, in
manager.run()
File "C:\Python27\lib\site-packages\flask_script__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "C:\Python27\lib\site-packages\flask_script__init__.py", line 383, in handle
res = handle(_args, *_config)
File "C:\Python27\lib\site-packages\flask_script\commands.py", line 216, in call
return self.run(_args, *_kwargs)
File "C:\Python27\lib\site-packages\flask_assets.py", line 422, in run
return impl.main(args)
File "C:\Python27\lib\site-packages\webassets\script.py", line 557, in main
return self.run_with_argv(argv)
File "C:\Python27\lib\site-packages\webassets\script.py", line 549, in run_with_argv
return self.run_with_ns(ns)
File "C:\Python27\lib\site-packages\webassets\script.py", line 539, in run_with_ns
return cmd.invoke(ns.command, args)
File "C:\Python27\lib\site-packages\webassets\script.py", line 373, in invoke
return function(**args)
File "C:\Python27\lib\site-packages\webassets\script.py", line 299, in call
file_path = bundle.resolve_output(self.environment)
File "C:\Python27\lib\site-packages\webassets\bundle.py", line 326, in resolve_output
output = ctx.resolver.resolve_output_to_path(ctx, self.output, self)
File "C:\Python27\lib\site-packages\flask_assets.py", line 201, in resolve_output_to_path
directory, rel_path, endpoint = self.split_prefix(ctx, target)
File "C:\Python27\lib\site-packages\flask_assets.py", line 152, in split_prefix
app = ctx.environment._app
AttributeError: 'Environment' object has no attribute 'environment'
The build command works. The flask-script manager was initialized with:
manager.add_command("assets", ManageAssets(assets))
Hello there, I think that webassets and the related Flask module are awesome and just had a few questions about the way files are read and structured within a Flask project.
Suppose we wish to keep track of 3 item types:
I think a suitable directory structure would probably look something like this:
flask_project/assets/less/... <- (1) Non-compiled assets
flask_project/assets/coffee/... <- (1) Non-compiled assets
flask_project/static/js/... <- (2) Compiled assets
flask_project/static/js/... <- (3) 3rd Party Libraries
flask_project/static/css/... <- (2) Compiled assets
flask_project/static/css/... <- (3) 3rd Party Libraries
I have been experimenting with Flask-Assets and can't seem to find a way to achieve this without doing something like this in the template:
{% assets filters="less", output="css/style.css",
"../assets/less/style.less", "../assets/less/import.less" %}
<link rel="stylesheet" type="text/css" media="screen" href="{{ ASSET_URL }}" />
{% endassets %}
I also attempted to use the ASSETS_LOAD_PATH config item but didn't have any luck.
Is there any way to specify the source directory independently from the destination directory?
Also another little question, is the cache really needed? For example, I pictured that it would work as follows.
Please let me know your thoughts and if I'm missing something :)
Thank you so much and keep up the great work!
Fotis
@miracle2k This has gotten a bit out of hand. There are 3 open issue open that have to do with the inability to get the correct version of of webassets. Moreover, it has made it quite difficult to get new installations up and breaks builds.
The cleanest solution is to eliminate the parse_version
function in setup.py entirely and simply update the specific version in setup.py as things progress. As stated in the Zen of Python, "Explicit is better than implicit", "Simple is better than complex", and "Readability counts". Unfortunately, right now I think this setup is in contradiction with each of these.
Specifically, how to tell flask to spit out the CDN hostname instead of /static/
depending on a config var. Should I override url_for
somehow or change how ASSET_URL
works?
I've searched the web and there doesn't seem to be one standard way to do this (in flask at all, regardless of flask-assets). Any advice would be appreciated.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.