Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use packaged assets with Flask-Assets

How can I bundle assets using Flask-Assets that exist outside of Flasks default static/ directory?

  • I have npm install downloading assets into bower_components/
  • I have other javascripts that exist in javascripts/
  • I am using Flasks app factory pattern, and no matter how I've tried configuring Flask-Assets - I cannot get around the assets instance not bound to an application, and no application in current context exception.

Any help would be appreciated, especially if you can just give me an example on how to manage raw + packaged assets outside your apps static/ directory :P

app structure

app/
    static/
    __init__.py
    assets.py
javascripts/
    app.js
bower_components/
    jquery.js
    jquery,pjax,js

app/assets.py

from flask.ext.assets import Bundle, Environment

js = Bundle(
    'bower_components/jquery.js',
    'bower_components/jquery.pjax.js',
    'javascripts/app.js'
    filters='jsmin',
    output='static/packed.js'
)

assets = Environment()

assets.register('js_all', js)

app/init.py

from flask import Flask
from app.assets import assets

app = Flask(__name__)
assets.init_app(app)
like image 512
user1236803 Avatar asked Feb 03 '26 05:02

user1236803


1 Answers

I checked Flask-Assets source and found this in the docstring of FlaskResolver class:

If a Environment.load_path is set, it is used to look up source files, replacing the Flask system. Blueprint prefixes are no longer resolved.

So you need to do the following in app/init.py:

from os.path import abspath, join

app = Flask(__name__)
assets.load_path = abspath(join(app.root_path, '..'))
assets.init_app(app)
like image 170
Audrius Kažukauskas Avatar answered Feb 05 '26 22:02

Audrius Kažukauskas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!