def configure_assets(app): assets = Environment(app) css = Bundle( 'bootstrap/bootstrap.min.css', 'dist/css/flat-ui.min.css', 'bootstrap-datetimepicker/css/bootstrap-datetimepicker.css', # 'bootstrap/bootstrap-theme.min.css', # 'others/select2/select2.min.css', # 'others/smartwizard/smart_wizard.css', # 'fonts/font-awesome.min.css', 'main.css', filters="cssmin", output='temp/common_packed.css') js = Bundle( 'dist/js/vendor/jquery.min.js', 'jquery/jquery.form.js', 'dist/js/vendor/video.js', 'dist/js/flat-ui.min.js', 'bootstrap-datetimepicker/js/bootstrap-datetimepicker.js', 'bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js', 'message.js', # 'others/particles/particles.js', # 'others/select2/select2.full.min.js', # 'others/jquery.sortable.min.js', # 'others/smartwizard/jquery.smartWizard.js', 'main.js', filters='jsmin', output='temp/common_packed.js') assets.register('css_common', css) assets.register('js_common', js)
def test_directory_auto(self): """Test how we resolve file references through the Flask static system by default (if no custom 'env.directory' etc. values have been configured manually). """ assert not 'directory' in self.env.config root = self.app.root_path assert get_all_bundle_files(Bundle('foo'), self.env) == [root + '/static/foo'] # Modules prefixes in paths are handled specifically. assert get_all_bundle_files(Bundle('module/bar'), self.env) == [ root + '/test_module/static/bar' ] # Prefixes that aren't valid module names are just considered # subfolders of the main app. assert get_all_bundle_files(Bundle('nomodule/bar'), self.env) == [ root + '/static/nomodule/bar' ] # In case the name of a app-level subfolder conflicts with a # module name, you can always use this hack: assert get_all_bundle_files(Bundle('./module/bar'), self.env) == [root + '/static/module/bar'] # Custom static folder self.app.static_folder = '/' assert get_all_bundle_files(Bundle('foo'), self.env) == ['/foo']
def create_app(): app = Flask(__name__, instance_relative_config=True, static_folder='../static/', static_url_path='/static', template_folder='pages') app.config.from_pyfile('settings.py') assets = Environment(app) db.init_app(app) #Compress All Assets js = Bundle('javascripts/vendor/jquery-1.9.1.min.js', 'javascripts/main.js', 'javascripts/plugins.js', 'javascripts/vendor/modernizr-2.6.2.min.js', 'javascripts/vendor/Underscore-1.5.1.js', 'javascripts/vendor/backbone-min.js', filters='jsmin', output='gen/packedjs.js') assets.register('js_all', js) css = Bundle('stylesheets/css/boilerplate_main.css', 'stylesheets/css/normalize.css', 'stylesheets/css/page.css', filters='cssmin', output='gen/packedcss.css') assets.register('css_all', css) return app
def gen_assets_url(assets): try: names = [split_namespec(a)[0] for a in assets] except ValueError: abort(400) is_js = reduce(lambda status, name: status and name.endswith('.js'), names, True) is_css = reduce(lambda status, name: status and name.endswith('.css'), names, True) output_name = asset_key(assets) gendir = os.path.join(current_app.static_folder, 'gen') if not os.path.exists(gendir): os.mkdir(gendir) # The file extensions here are for upstream servers to serve the correct content type: if is_js: # TODO: Move this !jquery.js to somewhere more relevant bundle = Bundle(assets_repo.require(*(['!jquery.js'] + assets)), output='gen/' + output_name + '.js', filters='uglipyjs') elif is_css: bundle = Bundle(assets_repo.require(*assets), output='gen/' + output_name + '.css', filters=['cssrewrite', 'cssmin']) else: abort(400) bundle.env = current_app.assets return bundle.urls()[0]
def register_assets(spec): for name, elements in spec.iteritems(): name, kind = path.splitext(name) rules = get_rules(kind) filemap = defaultdict(list) for element in yield_expanded(elements): _, extension = path.splitext(element) if isinstance(element, Depends): rules.kwargs[extension]['depends'] = element continue filemap[extension].append(element) contents = list(filemap.get(kind, [])) for compiled_extension, compiled_filters in rules[ 'compilers'].iteritems(): if compiled_extension in filemap: kwargs = rules.kwargs.get(compiled_extension, {}) contents.append( Bundle(*filemap[compiled_extension], filters=compiled_filters, debug=False, output="gen/%s.%%(version)s%s%s" % (name, compiled_extension, kind), **kwargs)) assets.register( name + kind, Bundle(*contents, filters=rules.final_filter, output="gen/%s.%%(version)s%s" % (name, kind), **rules.kwargs[kind]))
def init_webassets(flask_app, config): """ Initialize Flask-Assets extension. """ assets = Environment(flask_app) assets.debug = flask_app.debug dart_root = 'dart/web' if flask_app.debug else 'dart/build/web' assets.register("less", Bundle( "less/bootstrap/bootstrap.less", "less/font-awesome/font-awesome.less", filters="less", output="combined/bootstrap.css", depends="less/*.less" )) assets.register('dart', Bundle( dart_root + '/main.dart' )) assets.register("javascript", Bundle( 'js/d3.js', 'js/markdown.js', dart_root + '/packages/web_components/dart_support.js', dart_root + '/packages/browser/dart.js', output='combined/combined.js' ))
def configure_extensions(app): " put flask extensions on the application " from burddy.extensions import db, alembic, bootstrap, login_manager, assets from flask.ext.assets import Bundle db.init_app(app) alembic.init_app(app) bootstrap.init_app(app) login_manager.init_app(app) login_manager.login_view = 'user.login' # Web Assets scss = Bundle('plugins/bootstrap/dist/css/bootstrap.min.css', 'scss/admin.scss', 'scss/footer.scss', 'scss/header.scss', 'scss/main.scss', filters='scss', output='scss_all.css') js = Bundle('plugins/jquery/dist/jquery.min.js', 'plugins/bootstrap/dist/js/bootstrap.js', 'plugins/ckeditor/ckeditor.js', 'plugins/ace-builds/src/ace.js', output='js_all.js') assets.register('scss_all', scss) assets.register('js_all', js) assets.init_app(app)
def register(assets, bundles): bundles["demo_js"] = Bundle("../themes/demo/static/js/demo.js", filters='jsmin', output="assets/js/demo.js") bundles["demo_css"] = Bundle("../themes/demo/static/css/demo.css", filters='cssmin', output="assets/css/demo.css") fonts_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', '..', 'piko', 'static', 'assets', 'fonts')) images_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', '..', 'piko', 'static', 'assets', 'images')) if not os.path.isdir(fonts_path): os.makedirs(fonts_path) if not os.path.isdir(images_path): os.makedirs(images_path) for font in glob.glob("piko/themes/demo/static/fonts/*.*"): shutil.copy(font, fonts_path) #assets.add(Bundle(font, filters=(noop,), output="fonts/%s" % (os.path.basename(font)))) for image in glob.glob("piko/themes/demo/static/images/*.*"): shutil.copy(image, images_path) #assets.add(Bundle(image, filters=(noop,), output="images/%s" % (os.path.basename(image)))) return bundles
def test_directory_custom(self): """A custom root directory is configured.""" self.env.directory = '/tmp' assert get_all_bundle_files(Bundle('foo'), self.env) == ['/tmp/foo'] # We do not recognize references to modules. assert get_all_bundle_files(Bundle('module/bar'), self.env) == ['/tmp/module/bar']
def bundle_assets(app, minify=True): js_filters = ['yui_js'] if minify else None css_filters = ['yui_css'] if minify else None js = Bundle( 'js/google_maps.js', 'js/ajax.js', filters=js_filters, output='gen/packed.js', ) css = Bundle( 'css/style.css', 'css/responsive.css', 'css/fonts.css', filters=css_filters, output='gen/packed.css', ) assets = Environment() assets.register('js', js) assets.register('css', css) app.config['ASSETS_DEBUG'] = not minify assets.init_app(app)
def register_assets(assets_class): from flask.ext.assets import Bundle # script(src="{{ # script(src="{{ # script(src="{{ static_path('find-ui/bower_components/knockout/dist/knockout.js') # script(src="{{ static_path('find-ui/bower_components/lodash/lodash.min.js') # script(src="{{ static_path('find-ui/dist/app/js/common.js') }}") # script(src="{{ static_path('find-ui/dist/app/js/home/home.js') }}") if "common" not in assets_class: tempjs = Bundle( 'find-ui/bower_components/letteringjs/jquery.lettering.js', 'find-ui/bower_components/knockout/dist/knockout.js', 'find-ui/bower_components/lodash/lodash.min.js', 'find-ui/dist/app/js/common.js', filters='jsmin', output='compiled.js') assets_class.register('common', tempjs) if "home" not in assets_class: tempjs = Bundle( 'find-ui/bower_components/letteringjs/jquery.lettering.js', 'find-ui/bower_components/textillate/jquery.textillate.js', 'find-ui/dist/app/js/common.js', filters='jsmin', output='home.js') assets_class.register('home', tempjs)
def test_directory_custom(self): """A custom root directory is configured.""" self.env.load_path = [self.tempdir] self.create_files(['foo', 'module/bar']) print get_all_bundle_files(Bundle('foo'), self.env) assert get_all_bundle_files(Bundle('foo'), self.env) == [self.path('foo')] # We do not recognize references to modules. assert get_all_bundle_files(Bundle('module/bar'), self.env) == [self.path('module/bar')]
def create_app(instance_path=None, debug=False, test=False): use_instances = False if instance_path is not None: use_instances = True app = Flask(__name__, instance_relative_config=use_instances, instance_path=instance_path, template_folder="views", static_path='/static', static_url_path='/static') app.debug = debug app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') app.config.from_object('app.config') app.config.from_pyfile('config.py') if not test: CsrfProtect(app) assets = Environment(app) css_bundle = Bundle('less/main.less', output='css/main.css', filters='less') assets.register('css', css_bundle) js_bundle = Bundle('js/main.js', output="main.min.js", filters="rjsmin") assets.register('js', js_bundle) email = FlaskMailgunMessage(app) @app.route('/', methods=['GET', 'POST']) def index(): form = ApplicationForm() if form.validate_on_submit(): if form.squirrel.data: # ANTI SPAM YO app.logger.info('SECRET SQUIRREL') return redirect(url_for('index')) form_data = "name: {}\nemail: {}\nphone: {}\n\n".format( form.name.data, form.email.data, form.phone.data) app.logger.info(form_data) # send the email email.send(form_data) flash(app.config['THANKS_FLASH']) return redirect(url_for('index')) return render_template('index.jade', form=form) return app
def create_app(package_name, js_assets=None, css_assets=None, settings_override=None): """Flask app factory.""" app = Flask(package_name, instance_relative_config=True) app.config.from_pyfile('settings.cfg', silent=False) app.config.from_object(settings_override) assets = Environment(app) assets.url = '../static' common_css_assets = [ 'css/bootstrap.min.css', 'css/animations.css', 'css/superfish.css', 'css/prettyPhoto.css', 'css/style.css', 'css/colors/blue.css', 'css/theme-responsive.css', ] common_js_assets = [ 'js/jquery.min.js', 'js/bootstrap.min.js', 'js/handlebars.js', 'js/ember.js', 'js/jquery.cookie.js', 'js/jquery.ba-bbq.min.js', ] if js_assets is not None: js_assets = common_js_assets + js_assets else: js_assets = common_js_assets js_bundle = Bundle( *js_assets, filters='jsmin', output='gen/' + package_name + '.js' ) assets.register('js_all', js_bundle) if css_assets is not None: css_assets = common_css_assets + css_assets else: css_assets = common_css_assets css_bundle = Bundle( *css_assets, filters='cssmin', output='gen/' + package_name + '.css' ) assets.register('css_all', css_bundle) assets.init_app(app) return app
def create_app(config='dev'): """ Flask application factory :param str config: type of app to build, either "prod" or "dev" """ # Create flask application app = Flask(__name__) app.config.from_object('settings') app.config['ENV'] = config app.jinja_env.trim_blocks = True # Debug toolbar (when debug=true) debug_toolbar = DebugToolbarExtension(app) app.config['DEBUG_TB_PROFILER_ENABLED'] = True app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # Register Blueprints app.register_blueprint(views_base.base) app.register_blueprint(views_blog.blog) # Flask-Assets; bundles all css/js files in minifed file assets = Environment(app) css_all = Bundle('css/bootstrap-flatly.min.css', 'css/highlightjs.min.css', 'css/font-awesome.css', 'css/main.css', filters='cssmin', output='gen/style.css') js_all = Bundle('js/vendor/jquery.min.js', 'js/vendor/bootstrap.min.js', 'js/vendor/showdown-gfm.min.js', 'js/vendor/highlight.min.js', 'js/main.js', filters='jsmin', output='gen/libs.js') assets.register('css_all', css_all) assets.register('js_all', js_all) if app.config['DEBUG']: assets.debug = True app.config['ASSETS_DEBUG'] = True # Set up Flask-User babel = Babel(app) db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) # Init Flask-User and bind to app # Init the cache cache.init_app(app) Moment(app) # moment.js Misaka(app, autolink=True, # Misaka Markdown fenced_code=True, lax_html=True, strikethrough=True, superscript=True, tables=True, wrap=True) # Init Admin page admin = Admin(app, index_view=AdminMain(endpoint='admin')) admin.add_view(PostAdminView()) admin.add_view(NewPostView()) admin.add_view(ModelView(Comment, db.session)) static_path = os.path.join(BASE_DIR, 'app', 'static') admin.add_view(FileAdminView(static_path, '/static/', name='Static Files')) # Initialize DB db.init_app(app) return app
def create_app(db_uri='any'): app = Flask(__name__) app.config.from_object('myapp.default_config') app.config.from_pyfile(os.path.join(app.instance_path, 'config.py')) if db_uri == 'Test': init_engine(app.config['TEST_DATABASE_URI']) else: init_engine(app.config['DATABASE_URI']) #Register Blueprints app.register_blueprint(main_blueprint) app.register_blueprint(user_blueprint, url_prefix="/users") #App logging # app.logger.setLevel(logging.WARNING) # logger_handler = logging.FileHandler(os.path.join(app.config['LOG_LOCATION'], # 'app_errors.log')) # formatter = logging.Formatter('%(asctime)s %(levelname)s - %(message)s' # ' [in %(pathname)s:%(lineno)d]') # logger_handler.setFormatter(formatter) # app.logger.addHandler(logger_handler) @app.teardown_request def shutdown_session(exception=None): db_session.remove() @app.errorhandler(404) def page_not_found(e): return render_template('404.html') @app.errorhandler(500) def internal_error(exception): app.logger.exception(exception) return "Some Internal error has taken place." #Extensions registration bcrypt.init_app(app) login_manager.setup_app(app) login_manager.login_view = 'users.login' assets.init_app(app) #CSS assets registration css = Bundle('base.css') assets.register('css_all', css) #JS assets registration js = Bundle('base.js') assets.register('js_all', js) return app
def configure_assets(app): """ Configures asset Environment. """ # webassets seems to require the environment to be bound to an application # before you can change the environment options. assets.app = app # Configure assets Environment assets.versions = 'hash' assets.manifest = 'file://%s' % os.path.realpath( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static/assets/.static-manifest')) assets.cache = False assets.autobuild = assets.debug assets.url = app.config.get('CDN_URL') # Build main css bundle assets.register( 'css_main', Bundle( 'css/bootstrap.css', 'css/default.css', filters='cssmin', ), filters='cssrewrite', output='assets/css/main%(version)s.css', ) # paths for bower bundle bower_file = os.path.realpath( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static/assets/tmp/bower-paths.json')) f = open(bower_file) bower_paths = [ 'assets/%s' % path for path in json.loads(f.read()).values() ] assets.register( 'js_main', Bundle(Bundle(*bower_paths), 'assets/tmp/mustache-compiled-templates.min.js', Bundle('js/default.js', filters='jsmin'), output='assets/js/main.%(version)s.js')) # Trigger a build of the css_main bundle now, so that we can use it in # another bundle later if we want. assets['css_main'].urls() assets.register_externals(ExternalAssets([ 'img/*', ])) assets.config['external_assets_output_folder'] = 'assets/files/' app.jinja_env.globals['webasset'] = assets.external_assets.url
def init_bundles(): base_libs = [ 'vendor/jquery/dist/jquery.js', 'vendor/datatables/media/js/jquery.dataTables.js', 'scripts/dataTables.bootstrap.js', # 'vendor/bootstrap-sass-official/assets/javascripts/bootstrap.js', ] js = Bundle(*base_libs, filters=['jsmin'], output='scripts/fish-bundles.base.min.js') assets.register('js_base', js) app_files = [ 'scripts/main.coffee', 'scripts/create.coffee', 'scripts/header.coffee', ] js = Bundle(*app_files, filters=['coffeescript', 'jsmin'], output='scripts/fish-bundles.app.min.js') assets.register('js_app', js) app.config['COMPASS_PLUGINS'] = ['bootstrap-sass'] app.config['COMPASS_CONFIG'] = dict( css_dir="stylesheets", sass_dir="sass", images_dir="images", javascripts_dir="scripts", relative_assets=True, ) css_files = [ 'vendor/datatables/media/css/jquery.dataTables.css', 'stylesheets/dataTables.bootstrap.css', ] css = Bundle(*css_files, filters=['cssmin'], output='stylesheets/fish-bundles.base.min.css') assets.register('css_base', css) css_files = ['sass/main.scss'] css = Bundle(*css_files, depends=["**/*.scss"], filters=['compass', 'cssmin'], output='stylesheets/fish-bundles.min.css') assets.register('css_app', css) if app.debug: assets.auto_build = True assets.debug = True assets.manifest = "file" assets.cache = False
def test(self): """Make sure the "url" and "directory" config values are read from the Flask app. """ with self.app.test_request_context(): assert not 'url' in self.env.config assert Bundle('foo').urls(self.env) == ['/initapp_static/foo'] assert not 'directory' in self.env.config root = self.app.root_path assert get_all_bundle_files(Bundle('foo'), self.env) == [root + '/static/foo']
def assets_helper(*args, **kwargs): result = [] for f in args: try: result.append(assets[f]) except KeyError: result.append(f) bundle = Bundle(*result, **kwargs) urls = bundle.urls(env=assets) return urls
def bundle_javascripts(): vendor = Bundle( 'javascripts/vendor/browser-polyfill.js', 'javascripts/vendor/jquery.js', 'javascripts/vendor/fixedsticky.js', ) application = Bundle('javascripts/app.js', filters='browserify', output='build/app.js', depends=('javascripts/**', 'javascripts/**/*')) js = Bundle(vendor, application, filters='rjsmin', output='build/app.js') return js
def init(app): assets = Environment(app) js = Bundle(*app.config['JS_ASSETS'], output=app.config['JS_ASSETS_OUTPUT'], filters=app.config['JS_ASSETS_FILTERS']) css = Bundle(*app.config['CSS_ASSETS'], output=app.config['CSS_ASSETS_OUTPUT'], filters=app.config['CSS_ASSETS_FILTERS']) assets.register('js_all', js) assets.register('css_all', css)
def init_tasks(app): """ Extracts modules (task types) from global configuration :param app: Current Flask application instance :type app: Flask.Flask :return: Dictionary with instantiated *TaskType objects :rtype: dict """ task_types = {} loaders = {} enabled_tasks = app.config.get("ENABLED_TASKS", {}) for plugin, task in enabled_tasks.iteritems(): task_settings = import_string( "{plugin_name}.settings".format(plugin_name=plugin)) plugin_instance = import_string( "{plugin_name}".format(plugin_name=plugin)) settings = plugin_instance.configure(task_settings) task_instance = import_string( "{plugin_name}.models.task_types.{task}".format(plugin_name=plugin, task=task)) static_path = import_string(plugin).__path__[0] js_name = 'plugin_js_{task}'.format(task=task_instance.type_name) css_name = 'plugin_css_{task}'.format(task=task_instance.type_name) if len(task_instance.JS_ASSETS) > 0: js = Bundle(*map(lambda x: os.path.join(static_path, x), task_instance.JS_ASSETS), output="scripts/{name}.js".format(name=js_name), filters=app.config.get('JS_ASSETS_FILTERS', '')) app.assets.register(js_name, js) if len(task_instance.CSS_ASSETS) > 0: css = Bundle(*map(lambda x: os.path.join(static_path, x), task_instance.CSS_ASSETS), output="styles/{name}.css".format(name=css_name), filters=app.config.get('CSS_ASSETS_FILTERS', '')) app.assets.register(css_name, css) loaders[task_instance.type_name] = jinja2.PackageLoader(plugin) task_types[task_instance.type_name] = task_instance(settings=settings) app.jinja_loader = jinja2.ChoiceLoader( [app.jinja_loader, jinja2.PrefixLoader(loaders)]) return task_types
def test_url_auto(self): """Test how urls are generated if no 'url' is configured manually. """ assert not 'url' in self.env.config assert Bundle('foo').urls(self.env) == ['/app_static/foo'] # Urls for files that point to a module use that module's url prefix. assert Bundle('module/bar').urls(self.env) == ['/mod_static/bar'] # Try with a prefix that's not actually a valid module assert Bundle('nomodule/bar').urls(self.env) == ['/app_static/nomodule/bar'] # [Regression] Ensure that any request context we may have added # to the stack has been removed. from flask import _request_ctx_stack assert _request_ctx_stack.top is None
def register(self, name, *args, **kwargs): ext = args[0].split('.')[-1] filters = kwargs.get('filters', self.default_filters[ext]) output = kwargs.get('output', self.default_output[ext]) return super(Assets, self).register( name, Bundle(*args, filters=filters, output=output))
def check_and_compile_bundle(name, settings): if len(name) == 0: raise ValueError('The bundle name must have a length of more than 0') if not isinstance(settings['type'], str): raise ValueError( 'The "%s" bundle must have a string type associated with it' % name) if len(settings['type']) == 0: raise ValueError( 'The "%s" bundle type must have a type length of more than 0' % name) if len(settings['files']) == 0: raise ValueError('The "%s" bundle must have files associated with it' % name) # Check each file in bundle to make sure it exists. static_abs_path = os.path.abspath('static') for filename in settings['files']: if not os.path.isfile(os.path.join(static_abs_path, filename)): raise IOError('File "%s" in bundle "%s" does not exist.' % (filename, name)) if settings['filters'] is None: filters = None else: filters = ','.join(settings['filters']) if 'output' in settings: output = settings['output'] else: output = 'out/' + name + '.%(version)s' + '.' + settings['type'] return Bundle(*settings['files'], filters=filters, output=output)
def register_scss(): """Registers the Flask-Assets rules for scss compilation. This reads from ``config/scss.json`` to make these rules. We expire files using filenames: http://webassets.readthedocs.org/en/latest/expiring.html#expire-using-the-filename """ assets.url = app.static_url_path assets.config['SASS_PATH'] = app.config['SCSS_FOLDER'] with open('config/scss.json') as f: bundle_instructions = json.loads(f.read()) for _, bundle_set in bundle_instructions.iteritems(): output_folder = bundle_set['output_folder'] depends = bundle_set['depends'] for bundle_name, instructions in bundle_set['rules'].iteritems(): # Use filename expiration output_filename = (output_folder + instructions['output'].rstrip('.css') + '.%(version)s.css') bundle = Bundle(*instructions['inputs'], output=output_filename, depends=depends, filters=('scss', 'cssmin')) assets.register(bundle_name, bundle)
def _load_assets(): for name, asset_registry in _asset_registry.iteritems(): asset_files = [item for item in asset_registry['items']] asset_bundle = Bundle(*asset_files, filters=asset_registry['filters'], output=asset_registry['out']) assets.register(name, asset_bundle)
def test_custom_directory_and_url(self): """Custom directory/url are configured - this will affect how we deal with output files.""" # Create source source file, make it findable (by default, # static_folder) is set to a fixed subfolder of the test dir (why?) self.create_files({'a': ''}) self.app.static_folder = self.tempdir # Setup custom directory/url pair for output self.env.directory = self.tempdir self.env.url = '/custom' self.env.debug = False # Return build urls self.env.expire = False # No query strings assert Bundle('a', output='foo').urls(self.env) == ['/custom/foo'] # We do not recognize references to modules. assert Bundle('a', output='module/bar').urls(self.env) == ['/custom/module/bar']
def init_for(env): coaster.app.init_app(app, env) RQ(app) baseframe.init_app(app, requires=['hasjob'], ext_requires=[ 'baseframe-bs3', ('jquery.textarea-expander', 'jquery.cookie', 'jquery.sparkline', 'jquery.nouislider'), ('firasans', 'baseframe-firasans'), 'fontawesome>=4.0.0' ]) # TinyMCE has to be loaded by itself, unminified, or it won't be able to find its assets app.assets.register( 'js_tinymce', assets.require('!jquery.js', 'tinymce.js>=4.0.0', 'jquery.tinymce.js>=4.0.0')) app.assets.register( 'css_editor', Bundle('css/editor.css', filters=['cssrewrite', 'cssmin'], output='css/editor.packed.css')) from hasjob.uploads import configure as uploads_configure from hasjob.search import configure as search_configure uploads_configure() search_configure() mail.init_app(app) lastuser.init_app(app) lastuser.init_usermanager(UserManager(db, models.User))
def init_assets(self): css = Bundle( 'libs/bootstrap/dist/css/bootstrap.css', 'css/style.css', filters='cssmin', output='public/css/common.css' ) js = Bundle( 'libs/jquery/dist/jquery.js', 'libs/bootstrap/dist/js/bootstrap.js', filters='jsmin', output='public/js/common.js' ) assets.register('css_all', css) assets.register('js_all', js) assets.init_app(self.app)
def register_assets(app): _css_files = ["css/base.css", "css/app.css"] for module in LOADED_MODULES: for fname in get_files_from_module(module, "css", "css"): _css_files.append("api_v1_" + module + "/css/" + fname) css_all = Bundle( *_css_files, filters="cssmin", output="css/app.min.css" ) _js_files = list(get_files_in_directory("js/develop", ".js", excludes=["app.min.js", "app.js"])) for module in LOADED_MODULES: for fname in get_files_from_module(module, "js", "js"): _js_files.append("api_v1_" + module + "/js/" + fname) js_all = Bundle("js/develop/app.js", *_js_files, filters="uglifyjs", output="js/app.min.js") assets.init_app(app) # work around bug https://github.com/miracle2k/flask-assets/issues/54 assets.app = app assets.auto_build = app.debug assets.debug = app.debug assets.register("js_all", js_all) assets.register("css_all", css_all) if not app.debug: partials_template = '<script id="{path}" type="text/ng-template">{content}</script>' global _partials _partials = "" for module in LOADED_MODULES: for fname in get_files_from_module(module, "partials", "html"): # TODO: look at this hack. with app.test_request_context(): path = url_for("api_v1_" + module + ".static", filename="partials/" + fname) with open(os.path.join(APP_FOLDER, "projecto", "apiv1", module, "static", "partials", fname)) as g: content = g.read() _partials += partials_template.format(path=path, content=content) css_all.build() js_all.build()
def init_assets_environment(app, include_dependencies=True, auto_build=True): """Configure Flask webassets.""" # Configuration must be set directly on Flask.config because Environment # needs to have a Flask application in the context in order to do that. app.config['ASSETS_AUTO_BUILD'] = auto_build # We need a r.js version which supports stdout (https://github.com/jrburke/r.js/pull/620). app.config['RJS_BIN'] = path.join(app.config['STATIC_ROOT'], 'js', 'vendor', 'r.js') app.config['RJS_EXTRA_ARGS'] = read_config(path.join(app.config['DATA_ROOT'], 'r.js.conf')) register_filter(RJS) # 'less' requires lessc and node.js (see package.json). css_layout = Bundle(path.join('css', 'less', 'layout.less'), output=path.join('css', 'layout.min.css'), filters='less, cssmin', depends=files(path.join(app.static_folder, 'css', 'less'), '*.less')) css_errors = Bundle(path.join('css', 'less', 'errors.less'), output=path.join('css', 'errors.min.css'), filters='less, cssmin') # 'rjs' requires r.js and node.js. js_rjs = Bundle(path.join('js', 'build', 'main.js'), output=path.join('js', 'main.min.js'), filters='rjs', depends=files(path.join(app.static_folder, 'js', 'build'), '*.js')) # Hack: exclude dependencies in order to enable caching (this is a webassets issue). if not include_dependencies: css_layout.depends = [] css_errors.depends = [] js_rjs.depends = [] assets_env.register('css_layout', css_layout) assets_env.register('css_errors', css_errors) assets_env.register('js_rjs', js_rjs) assets_env.init_app(app)
LANGUAGES = requests.get((app.config['SUMO_URL'] + 'offline/get-languages')).json() LANGUAGES = json.dumps(LANGUAGES['languages']) # Sets up the assets assets = Environment(app) assets.auto_build = app.debug assets.debug = app.debug # we don't need this as manifest.appcache will change assets.url_expire = False css = Bundle( 'css/develop/gaia.css', 'css/develop/doc.css', 'css/develop/installer.css', 'css/develop/nav.css', 'css/develop/app.css', filters='cssmin', output='css/app.min.css' ) assets.register('css_all', css) scripts = ['js/develop/app.js'] for root, subdir, fnames in os.walk('static/js/develop'): for filename in fnames: if filename.endswith('.js') and filename != 'app.js': # get rid of te 'static/' scripts.append(os.path.join(root, filename)[7:]) js = Bundle(*scripts, filters='uglifyjs', output='js/app.min.js') assets.register('js_all', js)
login_manager = LoginManager() login_manager.init_app(app) bcrypt = Bcrypt(app) logger = app.logger ################ ASSETS MANAGEMENT ################ # right now just minification and concatenation assets = Environment(app) assets.url = app.static_url_path css_all = Bundle( 'css/*.css', filters='cssmin', output='dist/css_all.css' ) js_all = Bundle( 'js/vendor/jquery-1.11.0.min.js', # order matters 'js/vendor/*.js', 'js/*.js', filters='jsmin', output='dist/js_all.js' ) assets.register('js_all', js_all) assets.register('css_all', css_all) assets.add(js_all) assets.add(css_all)
app.config.update( TEMPLATES_AUTO_RELOAD = True ) assets = Environment(app) assets.url = app.static_url_path # for development # Don't cache otherwise it won't build every time assets.cache = False assets.manifest = False app.config['ASSETS_DEBUG'] = True scss = Bundle('style.scss', filters='pyscss', output='all.css') assets.register('scss_all', scss) scss.build() js_files = ['js/mustache.js', 'mustache/mustache-loader.js', 'js/mui.js', 'js/main.js'] js = Bundle(*js_files, filters='jsmin', output='packed.js') assets.register('js_all', js) js.build() assets.init_app(app) global case_bucket case_bucket = None def create_celery_app():