EzDevInfo.com

webassets

Asset management for Python web development.

Example of configuring Flask + AngularJS + PyJade (or other alternative to Jinja)

I am new to Flask and building a web app that uses Flask and AngularJS. My understanding is that the static directory is the place to store AngularJS files like javascript and templates.

I wonder if there is a stable alternative to Html/Jinja that I can use for templates. And if there is, how can I enable it to work with template files inside the static directory?

I was looking to PyJade but didn't get how to get it working with the web assets pipeline.

Would appreciate any example or recommendation.


Source: (StackOverflow)

Error while trying to use pyramid_webassets and pyramid_jinja2 together

I am trying to get my pyramid app to use pyramid_jinja2 and pyramid_webassets.

My main config function looks a little like this:

def main(global_config, **settings):
    engine = engine_from_config(settings, 'sqlalchemy.', encoding='utf-8')
    get_root = appmaker(engine)
    session_factory = session_factory_from_settings(settings)
    config = Configurator(settings=settings, root_factory=get_root)
    config.include('pyramid_handlers')
    config.include('pyramid_jinja2')
    config.add_jinja2_renderer('.html')
    config.add_jinja2_search_path('myapp:templates', name='.html')
    config.include('pyramid_webassets')
    config.add_jinja2_extension('webassets.ext.jinja2.AssetsExtension')
    assets_env = config.get_webassets_env()
    jinja2_env = config.get_jinja2_environment()
    jinja2_env.assets_environment = assets_env

After going through the docs multiple times it seems to be configured correctly but I keep getting the error:

jinja2_env.assets_environment = assets_env
AttributeError: 'NoneType' object has no attribute 'assets_environment'

Not sure as to why jinja2_env is remaining undefined. The only dependency should be pyramid_jinja2 which is definitely being used and set on the config object. Any insights or examples to configs with jinja2 and webassets would be much appreciated.


Source: (StackOverflow)

Advertisements

flask-assets- FilterError: stylus: subprocess returned a non-success result code: 1, stdout=, stderr=

I'm attempting to compile stylus files using flask-assets and webassets. This "just works" on the iMac in my office, but stylus is returning and exit code of 1 when I try to run the server on my desktop running Ubuntu 14.04.

I've tried installing stylus in the project directory and point STYLUS_BIN there, as well as installing stylus globally and setting STYLUS_BIN to 'usr/local/bin/stylus'. Either way produces an exit code of 1 when trying to run the server application. Any idea what I could be doing wrong?

Traceback - https://gist.github.com/anonymous/879979fbc9ed3da92b54


Source: (StackOverflow)

pip - installation of sub-dependencies overrides other packages on requirements.txt

my requirements file is like that :

https://github.com/sontek/pyramid_webassets/archive/38b0b9f9f4e36dc22b3a5c10eabf4d9228d97740.zip#egg=pyramid_webassets-0.0
https://github.com/miracle2k/webassets/archive/334d55c6bcfd091cb2d984777daf943acde0d364.zip#egg=webassets-0.8.dev

when running pip install -r requirements.txt I want it to install the specific version of pyramid_webassets, and then the specific webassets version (0.8.dev)

the problem is that pyramid_webassets have the webassets as sub-dependency, and it installs the latest of this package.

so the output of pip freeze is

Chameleon==2.14
Mako==0.9.1
MarkupSafe==0.18
PasteDeploy==1.5.2
WebOb==1.3.1
argparse==1.2.1
pyramid==1.4.5
pyramid-webassets==0.0
repoze.lru==0.6
translationstring==1.1
venusian==1.0a8
webassets==0.9
wsgiref==0.1.2
zope.deprecation==4.1.0
zope.interface==4.0.5

you might notice that webassets version is the latest (0.9) though I specified the version I want (0.8.dev).

I tried to reorder the list, adding the --upgrade flag- nothing helped.

any idea how can I install it and still having the required version of webassets?

Thanks.


soultion:

I found this commend useful:

cat requirements.txt | xargs -L1 pip install

that will install one by one the packages orderly

but we should add --upgrade for the last package so it'll upgrade it.


Source: (StackOverflow)

dustjs + webassets results to empty compiled file

I'm running python (2.7) with Flask with webassets (0.9) and i done all the steps described in the docs for running dustjs, but all results in an empty file. The strangest thing is that when I run dusty directly in the dir with my templates it works fine.

Here is my configs.

myapp.py

assets_env = Environment(app)

assets.py

common_dust = Bundle("dust/*", filters='dustjs', output='gen/dust_compiled.js')

templates/index.html


Source: (StackOverflow)

How to use Flask assets to set cache for static files

I used Flask assets in my project to combine all js and css files. Its working perfectly.

assets = Environment(app)
js = Bundle('js/jquery/jquery.js','js/owl.carousel.min.js',output='gen/packed.js')

assets.register('js_all', js)

css = Bundle('css/bootstrap.css','css/font-awesome.css','css/color.css',output='gen/packed.css')
assets.register('css_all', css)

Now i want to set expire days on static files. I checked the URL expiry part in doc. But i am confused. I want to set 30 days as expire. How can i achieve that goal using flask assets.


Source: (StackOverflow)

Webassets - exclude file in bundle

I have a directory and want to exclude a few files like Ant does, is this possible with webassets?

Or does if bundle could take a list or tuple, which doesn't seem to be the case?


Source: (StackOverflow)

Using "depends" in webassets bundles

I'm using webassets in my Flask application using Flask-Assets and I'm having trouble with the depends option when creating bundles.

In my case I'm bundling LESS files from the following directory structure:

/static
 \_ /css
     \_ /bootstrap
     |   \_ bootstrap.less // This file @imports variables.less and custom.less
     |   \_ variables.less
     \_ custom.less

My bundle looks like this:

css = Bundle(
    "css/bootstrap/bootstrap.less",
    filters="less, cssmin",
    output="dist/base.css",
    depends="**/*.less"
)

With these settings, the LESS files are rebuilt whenever a change is made to either bootstrap.less or custom.less but NOT variables.less.

From what I understand, the expression used for the depends option is a glob instruction and using the one above should simply go through all directories recursively and pick up any LESS files. However, it never seems to pick up on any changes made to variables.less.

In my attempts to fix this, I've tried the following options for depends:

  • "*.less" - Doesn't pick up anything (as it's searching in the root of the project directory, I believe, where there are no LESS files anyway)
  • "**/*.less, myproject/static/css/bootstrap/variables.less" - Doesn't pick up on any changes in any file at all.
  • "**/*.less, myproject/static/css/bootstrap/variables.less" - Same as the one above.
  • "myproject/static/css/bootstrap/variables.less" - Strangely enough, this picks up on changes made to both variables.less AND any other LESS files (such as custom.less).

In essence, the last item is the "solution" for my problem but I have no idea why it works the way it does, so it doesn't sit well with me. Can anyone provide an explanation or a nudge in the right direction here?

Thanks!


Source: (StackOverflow)

jason lewis basset did not show icons well in laravel 4

I have a problem with rendering css+html of the bootstrap theme in laravel 4. I by a admin template, and web browser show me something like that small part of html. I use jasonlewis basset to generate admin template. How to fix this? I use this in app\config\packages\jasonlewis\basset\config.php:

'collections' => array(

    'public' => function($collection)
    {
        $collection->directory('assets/css', function($collection)
        {
            $collection->add('bootstrap.min.css');
            $collection->add('jquery-ui-1.10.3.custom.css');
            $collection->add('fullcalendar.css');
            $collection->add('chosen.css');
            $collection->add('select2.css');
            $collection->add('jquery.cleditor.css');
            $collection->add('jquery.noty.css');
            $collection->add('noty_theme_default.css');
            $collection->add('elfinder.min.css');
            $collection->add('elfinder.theme.css');
            $collection->add('uploadify.css');
            $collection->add('jquery.gritter.css');
            $collection->add('font-awesome.min.css');
            $collection->add('font-awesome-ie7.min.css');
            $collection->add('glyphicons.css');
            $collection->add('halflings.css');
            $collection->add('dropzone.css');
            $collection->add('xcharts.min.css');
            $collection->add('jquery.easy-pie-chart.css');
            $collection->add('icheck/all.css');
            $collection->add('bootstrap-editable.css');
            $collection->add('lato300.css');
            $collection->add('lato.css');
            $collection->add('kausha.css');
            $collection->add('style.min.css');
            $collection->add('retina.min.css');
        })->apply('UriRewriteFilter')->apply('CssMin');

        $collection->directory('assets/js', function($collection)
        {
            $collection->add('html5.js');
            $collection->add('respond.min.js');
            $collection->add('jquery-2.0.3.min.js');
        })->apply('JsMin');
    },

    'admin' => function($collection)
    {
        $collection->directory('assets/css', function($collection)
        {
            $collection->add('bootstrap.min.css');
            $collection->add('jquery-ui-1.10.3.custom.css');
            $collection->add('fullcalendar.css');
            $collection->add('chosen.css');
            $collection->add('select2.css');
            $collection->add('jquery.cleditor.css');
            $collection->add('jquery.noty.css');
            $collection->add('noty_theme_default.css');
            $collection->add('elfinder.min.css');
            $collection->add('elfinder.theme.css');
            $collection->add('uploadify.css');
            $collection->add('jquery.gritter.css');
            $collection->add('font-awesome.min.css');
            $collection->add('font-awesome-ie7.min.css');
            $collection->add('glyphicons.css');
            $collection->add('halflings.css');
            $collection->add('dropzone.css');
            $collection->add('xcharts.min.css');
            $collection->add('jquery.easy-pie-chart.css');
            $collection->add('icheck/all.css');
            $collection->add('bootstrap-editable.css');
            $collection->add('lato300.css');
            $collection->add('lato.css');
            $collection->add('kausha.css');
            $collection->add('style.min.css');
            $collection->add('retina.min.css');
        })->apply('UriRewriteFilter')->apply('CssMin');

        $collection->directory('assets/js', function($collection)
        {
            $collection->add('html5.js');
            $collection->add('respond.min.js');
            $collection->add('jquery-2.0.3.min.js');
            //$collection->requireDirectory('../../../vendor/twbs/bootstrap/js');
            $collection->add('jquery-migrate-1.2.1.min.js');
            $collection->add('bootstrap.min.js');
            $collection->add('jquery-ui-1.10.3.custom.min.js');
            $collection->add('jquery.ui.touch-punch.min.js');
            $collection->add('jquery.sparkline.min.js');
            $collection->add('fullcalendar.min.js');
            $collection->add('excanvas.min.js');

            $collection->add('jquery.flot.min.js');
            $collection->add('jquery.flot.pie.min.js');
            $collection->add('jquery.flot.stack.min.js');
            $collection->add('jquery.flot.resize.min.js');
            $collection->add('jquery.flot.time.min.js');
            $collection->add('jquery.autosize.min.js');
            $collection->add('jquery.placeholder.min.js');
            $collection->add('moment.min.js');
            $collection->add('daterangepicker.min.js');
            $collection->add('jquery.easy-pie-chart.min.js');
            $collection->add('jquery.dataTables.min.js');
            $collection->add('dataTables.bootstrap.min.js');
            $collection->add('custom.min.js');
            $collection->add('core.min.js');
            $collection->add('pages/index.js');
        })->apply('JsMin');
    }

Source: (StackOverflow)

Issue using Flask-Assets to compile less files

I'm currently trying to set up a Flask web app, and trying to use Flask-Assets to compile my less files into minified css.

Here is my assets.py file that creates the bundle.

from flask_assets import Bundle

common_css = Bundle(
    'vendor/less/theme.less',
    filters='less',
    output='static/css/common.css',
    )

The error that I am getting is:

OSError: [Errno 2] No such file or directory

In the webassets documentation for the less filter, it says that:

This depends on the NodeJS implementation of less, installable via npm. To use the old Ruby-based version (implemented in the 1.x Ruby gem), see Less.

...

LESS_BIN (binary)
    Path to the less executable used to compile source files. By default, the filter will attempt to run lessc via the system path.

I installed less using $ npm install less, but for some reason it looks like webassets can't use it.

When I try to use different filters, then webassets can successfully create the bundle.

Thanks!


Source: (StackOverflow)

Using Flask-Assets with Flask-Mako

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?

Here is my app.py for the record:

import os
from flask import Flask, render_template
from flask.ext import assets
from flask import config
from flask.ext.mako import MakoTemplates
from flask.ext.mako import render_template

app = Flask(__name__)
app.config['ASSETS_DEBUG'] = True

mako = MakoTemplates(app)
env = assets.Environment(app)

# Tell flask-assets where to look for our coffeescript and sass files.
env.load_path = [
    os.path.join(os.path.dirname(__file__), 'js'),
    os.path.join(os.path.dirname(__file__), 'styles'),
]

coffee = assets.Bundle('**/*.coffee', filters='coffeescript', output="app.js")
env.register('coffee', coffee)

@app.route("/")
def index():
    return render_template('index.html', name='mako')


if __name__ == "__main__":
    app.run(debug=True)

Source: (StackOverflow)

Flask-Assets not working at all... = Insanity

I have simply tried setting up flask-assets (based on webassets), however just can't get it to work.

I have the standard setup;

  • python virtualenv
  • pip to install the bare essentials (flask, flask-assets)
  • sass ruby gem (for trying sass / scss)
  • less via npm (for trying lesscss)
  • jsmin via pip (for trying jsmin)

Config:

  • I have created a working homepage in Flask
  • static folder created (for css / js assets)
  • The css / js files are confirmed working (css background, js slider, etc)
  • Basically my development non-flask-assets site is working perfectly

I have followed the easy official guide here: flask-assets usage. I fully understand how to work with it (as per that page). I have even exact copy-pasted the code, & still can't get it working.

Some code I've tried (for lesscss): (of course I have working css in main.less)

from flask.ext.assets import Environment, Bundle
assets = Environment(app)
assets.debug = True

lesscss = Bundle('main.less', output='main.css', filters='less')
assets.register('less', lesscss)

Then in my template:

{% assets "less" %}
<link rel='nofollow' href="{{ ASSET_URL }}" rel="stylesheet">
{% endassets %}

However flask-assets just won't work. I've tried the same with sass, scss, & also jsmin (exact code copy-paste from the usage guide) - it still won't work.

  • I notice that the .webassets-cache folder is created, but is (always) empty...

Also; relevant error?; I expect it to create the main.css, but as it doesn't, I get an error in the browser (using app.debug = True & flask's built-in dev server):

webassets.exceptions.BuildError
BuildError: Nothing to build for <Bundle output=css/main.css, filters=[<webassets.filter.less.Less object at 0x7f4958dc6710>], contents=('css/main.less',)>, is empty

So; If I manually create an empty main.css, it loads the page (no error), however the main.css file is not filled with css so flask-assets / webassets in still not working.

I've also tried passing the assets object to the template in various ways just in case it's needed (although no documentation states this) - that didn't work.

It's been driving me crazy. Any pointers would be appreciated.
Thank you


Source: (StackOverflow)

Why am I getting KeyError: "Django settings doesn't define RESOLVER"?

I am getting the error below:

(testassets)➜  testassets git:(master) ✗ django-admin.py test
Creating test database for alias 'default'...
E
======================================================================
ERROR: test_get_site_root_with_settings_overrides (app.tests.AssetsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Volumes/fifteen5cs/testassets/app/tests.py", line 27, in test_get_site_root_with_settings_overrides
    http_client.get('/')
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/test/client.py", line 473, in get
    response = super(Client, self).get(path, data=data, **extra)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/test/client.py", line 280, in get
    return self.request(**r)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/test/client.py", line 444, in request
    six.reraise(*exc_info)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Volumes/fifteen5cs/testassets/app/views.py", line 9, in index
    context_instance=RequestContext(request))
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 29, in render_to_response
    return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/template/loader.py", line 169, in render_to_string
    return t.render(context_instance)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/template/base.py", line 140, in render
    return self._render(context)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/test/utils.py", line 85, in instrumented_test_render
    return self.nodelist.render(context)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/template/base.py", line 840, in render
    bit = self.render_node(node, context)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django/template/debug.py", line 78, in render_node
    return node.render(context)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django_assets/templatetags/assets.py", line 72, in render
    for url in bundle.urls():
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/webassets/bundle.py", line 783, in urls
    for bundle, extra_filters, new_ctx in self.iterbuild(ctx):
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/webassets/bundle.py", line 679, in iterbuild
    for bundle, _ in self.resolve_contents(ctx):
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/webassets/bundle.py", line 233, in resolve_contents
    result = ctx.resolver.resolve_source(ctx, item)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/webassets/bundle.py", line 50, in __getattr__
    return self.getattr(self._parent, item)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/webassets/bundle.py", line 58, in getattr
    return getattr(object, item)
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/webassets/env.py", line 675, in _get_resolver
    return self._storage['resolver']
  File "/Users/paul/.pyenv/versions/testassets/lib/python2.7/site-packages/django_assets/env.py", line 62, in __getitem__
    self._transform_key(key))
KeyError: "Django settings doesn't define RESOLVER"

----------------------------------------------------------------------
Ran 1 test in 0.325s

FAILED (errors=1)
Destroying test database for alias 'default'...

I have semi-linked this error to the use of the Django utils function django.test.utils.override_settings within one of my unit tests (shown below)

  1 from django.test.utils import override_settings
  2 from django.utils.unittest.case import TestCase
  3 from django.test.client import Client
  4
  5
  6 OVERRIDE_SETTINGS = {
  7     'DEBUG': True,
  8     'ASSETS_DEBUG': True,
  9     'ASSETS_AUTO_BUILD': True,
 10     'ASSETS_URL_EXPIRE': False,
 11     'ASSETS_CACHE': False,
 12     'ASSETS_MANIFEST': False,
 13     'ASSETS_VERSIONS': False,
 14 }
 15
 16
 17 class AssetsTestCase(TestCase):
 18     def test_get_site_root_with_settings_overrides(self):
 19         http_client = Client()
 20         # import pdb;pdb.set_trace()
 21         settings_override = override_settings(**OVERRIDE_SETTINGS)
 22         settings_override.enable()
 23         http_client.get('/')
 24         settings_override.disable()
 25
 26         settings_override.enable()
 27         http_client.get('/')
 28         settings_override.disable()

(NB. The exception is raised during the second request!)

The code base that I am working on that first presented this issue is too large and private to share so I have stripped down the project to a small amount of code that still creates the issue. That mini project can be found here https://github.com/logston/testassets.

I have spent over two days trying to determine where exactly this error is coming from and why it occurs during the second request but not the first. I have tried a number of permutations of unit tests. Interestingly, if I create a second unit test, one that does not enable settings overrides (eg. like the one below) and name that test such that it runs first during testing, the test suite passes. If I place that same unit test after the test_get_site_root_with_settings_overrides unit test, both will fail.

      def test_get_site_root(self):
          http_client = Client()
          http_client.get('/')

          http_client.get('/')

Any help on this issue would be immensely appreciated.

Finally, the only issue that I can find that speaks of the same or a similar problem is here: https://github.com/miracle2k/django-assets/issues/44

UPDATE 2015/01/12

The issue seems to be related to the use of signals. I have stripped the above failing test down to the following:

from django.test.utils import override_settings
from django.utils.unittest.case import TestCase
from django_assets.env import get_env


class AssetsTestCase(TestCase):
    def test(self):
        settings_override = override_settings()
        settings_override.enable()
        get_env().resolver
        settings_override.disable()

        settings_override.enable()
        get_env().resolver
        settings_override.disable()

Source: (StackOverflow)

How to compile multiple less files into multiple corresponding css files using webassets

I have the following Bundle configuration:

less = Bundle('**/*.less',
          filters='less', output='static/less.%(version)s.css')

Is it possible to compile the different less files into corresponding css files (in debug mode)? This configuration creates one css file.


Source: (StackOverflow)

Tell Webassets not to minify some code

I am using Flask Assets which uses Webassets. It does a great job of stripping my HTML.

However it strips whitespace in one area where I do not want whitespace to be stripped. Is there a way to tell webassets not to strip the whitespace from one area of code?


Source: (StackOverflow)