def create_app(config_name='Config'): app = Flask(__name__) config_name = os.getenv('APP_SETTINGS', config_name) app.config.from_object(f'config.{config_name}') # Set the secret key to some random bytes. Keep this really secret! app.secret_key = app.config.get('OPS_UI_SECRET') if app.config['IN_GCP'] == 'true': app.wsgi_app = ProxyFix(app.wsgi_app) logger_initial_config(app.config) logger = wrap_logger(logging.getLogger(__name__)) logger.info('Starting Census Response Operations UI', app_log_level=app.config['LOG_LEVEL'], environment=app.config['ENVIRONMENT']) assets = Environment(app) assets.url = app.static_url_path scss_min = Bundle('css/*', 'css/fonts/*', 'css/components/*', filters=['cssmin'], output='minimised/all.min.css') assets.register('scss_all', scss_min) js_min = Bundle('js/*', filters='jsmin', output='minimised/all.min.js') assets.register('js_all', js_min) app.before_request( partial(log_iap_audit, iap_audience=app.config['IAP_AUDIENCE'])) setup_blueprints(app) return app
def _bundle_3rd_party_css(env, debug=False): """Bundle any thrid party CSS files.""" if debug: bundle = Bundle(path.join('css', 'bootstrap.css'), path.join('css', 'select2.css'), path.join('css', 'prettify.css'), path.join('css', 'wysiwyg-color.css'), path.join('css', 'bootstrap-wysihtml5.css'), path.join('css', 'uploadify.css'), path.join('css', 'uploadifive.css'), path.join('css', 'fineuploader-3.3.1.css'), output=path.join('..', '..', APP_NAME, 'static', 'css', 'lib.css')) else: bundle = Bundle(path.join('css', 'min', 'bootstrap.min.css'), path.join('css', 'select2.css'), path.join('css', 'prettify.css'), path.join('css', 'wysiwyg-color.css'), path.join('css', 'bootstrap-wysihtml.css'), path.join('css', 'uploadify.css'), path.join('css', 'uploadifive.css'), path.join('css', 'fineuploader-3.3.1.css'), output=path.join('..', '..', APP_NAME, 'static', 'css', 'lib.css')) env.add(bundle) resp_bundle = Bundle(path.join('css', 'bootstrap-responsive.css'), output=path.join('..', '..', APP_NAME, 'static', 'css', 'responsive.css')) env.add(resp_bundle)
def setup(self): # Setup the assets environment. assets_env = AssetsEnvironment('', '') self.foo_bundle = Bundle() self.bar_bundle = Bundle() assets_env.register('foo_bundle', self.foo_bundle) assets_env.register('bar_bundle', self.bar_bundle) # Inject a mock bundle class into the Jinja2 extension, so we # can check on what exactly it does. test_instance = self class MockBundle(Bundle): urls_to_fake = ['foo'] def __init__(self, *a, **kw): Bundle.__init__(self, *a, **kw) self.env = assets_env # Kind of hacky, but gives us access to the last Bundle # instance used by the extension. test_instance.the_bundle = self def urls(self, *a, **kw): return self.urls_to_fake self._old_bundle_class = AssetsExtension.BundleClass AssetsExtension.BundleClass = self.BundleClass = MockBundle # Setup the Jinja2 environment. self.jinja_env = JinjaEnvironment() self.jinja_env.add_extension(AssetsExtension) self.jinja_env.assets_environment = assets_env
def _bundle_3rd_party_js(env, debug=False): """Combine thrid party js libs into libs.js. For debug, they are left uncompressed. For production the minified versions are used. We suggest using hte vendor supplied minified version of each library. """ JSPATH = path.join('js', 'lib') if debug: all_js = Bundle(path.join(JSPATH, 'json2.js'), path.join(JSPATH, 'jquery.js'), path.join(JSPATH, 'underscore.js'), path.join(JSPATH, 'backbone.js'), path.join(JSPATH, 'bootstrap.js'), path.join(JSPATH, 'leaflet.js'), path.join(JSPATH, 'bootstrap-typeahead-improved.js'), output=path.join('..', 'static', 'script', 'libs.js')) else: JSPATH = path.join(JSPATH, 'min') all_js = Bundle(path.join(JSPATH, 'json2.min.js'), path.join(JSPATH, 'jquery-min.js'), path.join(JSPATH, 'underscore-min.js'), path.join(JSPATH, 'backbone-min.js'), path.join(JSPATH, 'bootstrap-min.js'), path.join(JSPATH, 'leaflet-min.js'), path.join(JSPATH, 'bootstrap-typeahead-improved-min.js'), output=path.join('..', 'static', 'script', 'libs.js')) env.add(all_js) if debug: all_js.build()
def settings_func(basedir): from optimus.conf.model import SettingsModel from webassets import Bundle settings = SettingsModel() settings.load_from_kwargs( DEBUG=True, PROJECT_DIR=basedir, SITE_NAME="basic_i18n", SITE_DOMAIN="localhost", SOURCES_DIR=os.path.join(basedir, "sources"), TEMPLATES_DIR=os.path.join(basedir, "sources", "templates"), PUBLISH_DIR=os.path.join(basedir, "_build/dev"), STATIC_DIR=os.path.join(basedir, "_build/dev", "static"), STATIC_URL="static/", LOCALES_DIR=os.path.join(basedir, "locale"), LANGUAGE_CODE="en_US", LANGUAGES=("en_US", "fr_FR"), BUNDLES={ "modernizr_js": Bundle( "js/modernizr.src.js", filters=None, output="js/modernizr.min.js" ), "app_css": Bundle( "css/app.css", filters=None, output="css/app.min.css" ), "app_js": Bundle("js/app.js", filters=None, output="js/app.min.js"), }, FILES_TO_SYNC=(("css", "css"),), ) return settings
def test_register_dict(self): """Register a bunch of bundles at once.""" a = Bundle() b = Bundle() self.m.register({'foo': a, 'bar': b}) assert self.m['foo'] == a assert self.m['bar'] == b
def _bundle_3rd_party_js(app, env, debug=False): """Combine thrid party js libs into libs.js. For debug, they are left uncompressed. For production the minified versions are used. We suggest using hte vendor supplied minified version of each library. """ JSPATH = path.join('js', 'lib') if debug: scripts = () if not scripts: return all_js = Bundle(*scripts, output=path.join('..', '..', app, 'static', 'script', 'libs.js')) else: JSPATH = path.join(JSPATH, 'min') scripts = () if not scripts: return all_js = Bundle(*scripts, output=path.join('..', '..', app, 'static', 'script', 'libs.js')) env.add(all_js) if debug: all_js.build()
def run(self): from webassets import Bundle from webassets import Environment from webassets.script import CommandLineEnvironment css = Bundle('curious/src/css/app.css', output='curious/dist/curious.css') js = Bundle('curious/src/js/*.js', output='curious/dist/curious.js') jsm = Bundle('curious/src/js/*.js', filters='jsmin', output='curious/dist/curious.min.js') jst = Bundle('curious/src/html/*.html', filters='jst', output='curious/dist/curious_jst.js') assets_env = Environment('./curious/static') assets_env.cache = self.cache_dir assets_env.register('css', css) assets_env.register('js', js) assets_env.register('jsmin', jsm) assets_env.register('jst', jst) log = logging.getLogger('webassets') log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) cmdenv = CommandLineEnvironment(assets_env, log) cmdenv.build()
def compile_pages_and_assets(dev=False): compiledSass = '' sass_files_to_compile = ['main.scss'] for sassFile in sass_files_to_compile: # with open('resources/css/scss/'+sassFile, 'r') as thisfile: # SassData=thisfile.read() compiledSass += sass.compile(filename='resources/css/scss/'+sassFile, include_paths='resources/css/scss/vendor/') with open('resources/css/sass.css', 'w') as outputFile: outputFile.write(compiledSass) if(dev): all_js = Bundle('**/*.js', filters='noop', output='packed.js') all_css = Bundle('**/*.css', filters='noop', output="main.css") else: all_js = Bundle('**/*.js', filters='jsmin', output='packed.js') all_css = Bundle('**/*.css', filters='cssmin', output="main.css") jinja_env = Jinja2Environment(extensions=[AssetsExtension]) jinja_env.loader = FileSystemLoader('.') assets_env = AssetsEnvironment(url='/assets', directory='resources') assets_env.register('all_js', all_js) assets_env.register('all_css', all_css) jinja_env.assets_environment = assets_env pages = [] pages_dir = 'pages' for path, subdirs, files in os.walk(pages_dir): for name in files: pages.append(os.path.join(path, name)[6:]) # print(pages) for page in pages: thisTemplate = jinja_env.get_template('pages/' + page) thisTempRendered = thisTemplate.render() file_name = 'output/' + page body_content_location = 'output/content/' + page pathlib.Path(os.path.dirname(file_name)).mkdir(parents=True, exist_ok=True) pathlib.Path(os.path.dirname(body_content_location)).mkdir(parents=True, exist_ok=True) with open(file_name, 'w') as tempFile: tempFile.write(thisTempRendered) # This bit is used for my ajax shenanigans # anything you want on a page needs to go on body though... result = re.search('<body>(.*)<\/body>', '"' + thisTempRendered.replace('"', '\"').replace('\n',' ') + '"') # print(result) onlyTheBodyPart = result.group(1) with open(body_content_location, 'w') as tempFile: tempFile.write(onlyTheBodyPart) src = 'resources' dst = 'output/assets' filelist = [] files = ['main.css', 'packed.js'] for filename in files: filelist.append(filename) fullpath = src + '/' + filename shutil.move(os.path.join(src, filename), os.path.join(dst, filename))
def __init__(self): self._plugin_asset_env = PluginEnvironment('Collaboration', os.path.dirname(__file__), 'Collaboration') self._plugin_asset_env.register('collaboration_js', Bundle('js/Collaboration.js', 'js/bookings.js', filters='rjsmin', output="Collaboration_%(version)s.min.js")) self._plugin_asset_env.register('collaboration_css', Bundle('css/Style.css', filters='cssmin', output="Collaboration_%(version)s.min.css"))
def get_assets_css_env(self, code_path, output_path): """ The directory structure of assets is: output_path static css js """ output_path = os.path.join(output_path, 'static') assets_env = Environment(output_path, '/static', debug=self.args.debug) assets_env.config['compass_config'] = { 'additional_import_paths': [os.path.join(code_path, 'scss-mixins')], #'sass_options': "cache: False", ??? i can't get it. 'http_path': "/static", } css_list = [] scss_list = [] if "css_or_scss" in self.config.data: for filename in self.config.data["css_or_scss"]: if self.args.verbose: print('Adding filename: %s' % (filename)) ext = os.path.splitext(filename)[1] if ext == '.scss': scss_list.append(filename) elif ext == '.css': css_list.append(filename) else: raise Exception( 'Bad extension: is %s instead of css/scss' % ext) if len(css_list) or len(scss_list): css_bundle = Bundle(*css_list) scss_bundle = [] for scss_file in scss_list: if self.args.verbose: print('Processing filename: %s' % (scss_file)) try: xxx = Bundle( scss_file, filters='compass', output=scss_file + '.css', ) scss_bundle.append(xxx) except Exception as error: print("ERROR processing filename '%s': %s" % (scss_file, error)) css = Bundle(css_bundle, *scss_bundle, filters='cssutils,cssrewrite', output='packed.css') assets_env.register('css', css) return assets_env
def _bundle_app_less(env, debug): """Compile and minify appname's less files into appname.css.""" bundle = Bundle(Bundle(path.join('less', 'appname.less'), filters='less'), output=path.join('..', 'static', 'css', 'appname.css')) if not debug: bundle.filters = 'cssmin' env.add(bundle)
def bundles(cls, *sources): li = [] for i in sources: li.append( Bundle( "js/%s.iced" % i, output="built/%s.js" % i, filters=[cls] ) ) return Bundle(*li)
def main(global_config: Dict[str, str], **settings: str) -> PrefixMiddleware: """Configure and return a Pyramid WSGI application.""" config = Configurator(settings=settings) config.include('cornice') config.include('pyramid_session_redis') config.include('pyramid_webassets') # include database first so the session and querying are available config.include('tildes.database') config.include('tildes.auth') config.include('tildes.jinja') config.include('tildes.json') config.include('tildes.routes') config.add_webasset('javascript', Bundle(output='js/tildes.js')) config.add_webasset('javascript-third-party', Bundle(output='js/third_party.js')) config.add_webasset('css', Bundle(output='css/tildes.css')) config.add_webasset('site-icons-css', Bundle(output='css/site-icons.css')) config.scan('tildes.views') config.add_tween('tildes.http_method_tween_factory') config.add_request_method(is_safe_request_method, 'is_safe_method', reify=True) # Add the request.redis request method to access a redis connection. This # is done in a bit of a strange way to support being overridden in tests. config.registry['redis_connection_factory'] = get_redis_connection # pylint: disable=unnecessary-lambda config.add_request_method( lambda request: config.registry['redis_connection_factory'](request), 'redis', reify=True, ) # pylint: enable=unnecessary-lambda config.add_request_method(check_rate_limit, 'check_rate_limit') config.add_request_method(current_listing_base_url, 'current_listing_base_url') config.add_request_method(current_listing_normal_url, 'current_listing_normal_url') app = config.make_wsgi_app() force_port = global_config.get('prefixmiddleware_force_port') if force_port: prefixed_app = PrefixMiddleware(app, force_port=force_port) else: prefixed_app = PrefixMiddleware(app) return prefixed_app
def _bundle_3rd_party_css(app_path, env, debug=False): """Bundle any thrid party CSS files.""" if debug: bundle = Bundle(path.join('css', 'bootstrap.css'), output=path.join(app_path, 'css', 'lib.css')) else: bundle = Bundle(path.join('css', 'min', 'bootstrap.min.css'), output=path.join(app_path, 'css', 'lib.css')) env.add(bundle)
def get_template_namespace(self): _ = super(BaseHandler, self).get_template_namespace() self.assets = Environment( os.path.join(os.path.dirname(__file__), '../static'), '/static') css_all = Bundle('css/bootstrap.min.css', 'css/material.min.css', Bundle('css/schoolcms.css', 'css/dropdown.css', filters='cssmin'), 'outdatedbrowser/outdatedbrowser.min.css', output='dict/plugin.min.css') js_all = Bundle(Bundle('outdatedbrowser/outdatedbrowser.min.js', 'react-0.13.2/react-with-addons.min.js', 'js/jquery-2.1.3.min.js', 'js/bootstrap.min.js', 'js/react-bootstrap.min.js', 'js/react-mini-router.min.js', 'js/marked.min.js', 'js/material.min.js', 'js/isMobile.min.js', 'js/moment-with-locales.min.js', 'js/dropdown.js', filters='jsmin'), Bundle('schoolcms/init.jsx', 'schoolcms/mixin/*.jsx', 'schoolcms/component/*.jsx', 'schoolcms/page/*.jsx', filters=('react', 'jsmin')), output='dict/plugin.min.js') self.assets.register('css_all', css_all) self.assets.register('js_all', js_all) _['css_urls'] = self.assets['css_all'].urls() _['js_urls'] = self.assets['js_all'].urls() _['system_name'] = options.system_name _['SERVER_DEBUG'] = options.server_debug _['ip'] = self.request.remote_ip _['system_version'] = system_version _['_host'] = self.request.host _['_protocol'] = self.request.protocol if self.current_user: groups = GroupList.get_user_groups(self.current_user.key, self.sql_session) else: groups = [] _['current_user'] = self.current_user.to_dict( ) if self.current_user else None _['current_groups'] = groups # Call this to set the cookie self.xsrf_token return _
def _bundle_app_less(app, env, debug): """Compile and minify demo's less files into demo.css.""" bundle = Bundle(Bundle(path.join('less', '%s.less' % (app.lower(), )), filters='less'), output=path.join('..', '..', app, 'static', 'css', '%s.css' % (app.lower(), ))) if not debug: bundle.filters = 'cssmin' env.add(bundle)
def _bundle_3rd_party_css(env, debug=False): """Bundle any thrid party CSS files.""" if debug: bundle = Bundle(path.join('css', 'bootstrap.css'), path.join('css', 'leaflet.css'), path.join('css', 'leaflet.ie.css'), output=path.join('..', 'static', 'css', 'lib.css')) else: bundle = Bundle(path.join('css', 'min', 'bootstrap.min.css'), path.join('css', 'leaflet.css'), path.join('css', 'leaflet.ie.css'), output=path.join('..', 'static', 'css', 'lib.css')) env.add(bundle)
def register_all_css(env): fonts_sass = Bundle('sass/partials/_fonts.scss', filters=('pyscss', 'csscompressor'), output='css/indico_fonts_%(version)s.min.css') chartist_css = Bundle( 'css/lib/chartist.js/chartist.scss', 'css/lib/chartist.js/settings/_chartist-settings.scss', filters=('pyscss', 'csscompressor'), output='css/chartist_css_%(version)s.min.css') dropzone_css = Bundle('css/lib/dropzone.js/dropzone.css', 'sass/custom/_dropzone.scss', filters=('pyscss', 'csscompressor'), output='css/dropzone_css_%(version)s.min.css') selectize_css = Bundle('css/lib/selectize.js/selectize.css', 'css/lib/selectize.js/selectize.default.css', filters='csscompressor', output='css/selectize_css_%(version)s.min.css') jqplot_css = Bundle('css/lib/jquery.jqplot.css', filters='csscompressor', output='css/jqplot_%(version)s.min.css') base_css = Bundle(*namespace( 'css', 'Default.css', 'timetable.css', 'calendar-blue.css', 'jquery-ui.css', 'lib/angular.css', 'lib/jquery.qtip.css', 'lib/jquery.multiselect.css', 'lib/jquery.multiselect.filter.css', 'lib/jquery.typeahead.css', 'lib/fullcalendar.css', 'lib/outdatedbrowser.css', 'jquery.colorbox.css', 'jquery-ui-custom.css', 'jquery.colorpicker.css'), filters=('csscompressor', 'indico_cssrewrite'), output='css/base_%(version)s.min.css') screen_sass = Bundle('sass/screen.scss', filters=('pyscss', 'indico_cssrewrite', 'csscompressor'), output="sass/screen_sass_%(version)s.css", depends=SASS_BASE_MODULES) env.register('base_css', base_css) env.register('jqplot_css', jqplot_css) env.register('dropzone_css', dropzone_css) env.register('selectize_css', selectize_css) env.register('chartist_css', chartist_css) # SASS/SCSS env.register('screen_sass', screen_sass) env.register('fonts_sass', fonts_sass) # Build a bundle with customization CSS if enabled custom_css_files = _get_custom_files('scss', '*.scss') if custom_css_files: env.register( 'custom_sass', Bundle(*custom_css_files, filters=('pyscss', 'csscompressor'), output='sass/custom_sass_%(version)s.css'))
def test_build_failure(self): """If one bundle fails to build, the command continues, but returns an error code in the end.""" def failing_filter(*a, **kw): raise BuildError() self.create_files(['file']) a = Bundle('file', filters=failing_filter, output='outA') self.assets_env.register('a', a) b = Bundle('file', output='outB') self.assets_env.register('b', b) # build() returns an error code assert self.cmd_env.build() == 2 # the second bundle will have been built, event though the first failed assert self.exists('outB') assert not self.exists('outA')
def include_js(config): libraries = Bundle('js/jquery.min.js', 'js/jquery-ui.min.js', 'js/jquery.nano.js', 'js/angular.js', 'js/angular-filter.min.js', 'js/angular-animate.js', 'js/nprogress.js', 'js/chosen.jquery.js', 'js/difflib.js', 'js/diffview.js', 'js/crossfilter.js', 'js/dagre-d3.min.js', 'js/graphlib-dot.min.js', 'js/clipboard.js', 'js/angular-drag-and-drop-lists.js', 'js/uikit.js', 'js/components/grid.js', 'js/components/accordion.js', 'js/components/pagination.js', 'js/components/autocomplete.js', 'js/components/notify.js', 'js/components/sortable.js', 'js/components/sticky.js', 'js/components/upload.js', 'js/components/datepicker.js', 'js/components/search.js', 'js/components/tooltip.js', 'js/lati.app.js', filters='jsmin', output='js/min-libs.%(version)s.js') config.add_webasset('jslibraries', libraries)
def include_css(config): '''Definicja modulow CSS ''' theme = '.almost-flat' css = Bundle('css/uikit%s.css' % theme, 'css/components/accordion%s.css' % theme, 'css/components/autocomplete%s.css' % theme, 'css/components/datepicker%s.css' % theme, 'css/components/dotnav%s.css' % theme, 'css/components/form-advanced%s.css' % theme, 'css/components/form-file%s.css' % theme, 'css/components/form-password%s.css' % theme, 'css/components/form-select%s.css' % theme, 'css/components/notify%s.css' % theme, 'css/components/placeholder%s.css' % theme, 'css/components/progress%s.css' % theme, 'css/components/search%s.css' % theme, 'css/components/slidenav%s.css' % theme, 'css/components/slider%s.css' % theme, 'css/components/sticky%s.css' % theme, 'css/components/tooltip%s.css' % theme, 'css/components/upload%s.css' % theme, 'css/layout.css', filters='cssmin', output='css/min-css.%(version)s.css') config.add_webasset('css', css)
def get_bundle_for(ext, filters=None): dirname = pathlib.Path('assets/static') / f'_{ext}' files = [ str(f).replace('assets/static/', '') for f in dirname.rglob(f'**/*.{ext}') ] return Bundle(*files, filters=filters, output=f'css/site.{ext}')
def test_contains(self): """Test __contains__. """ b = Bundle() self.m.register('foo', b) assert 'foo' in self.m assert not 'bar' in self.m
def test_anon_bundle(self): """Self registering an anonymous bundle. """ b = Bundle() self.m.add(b) assert len(self.m) == 1 assert list(self.m) == [b]
def test_single_bundle(self): """Test self.m.registering a single ``Bundle`` object. """ b = Bundle() self.m.register('foo', b) assert self.get() == b
def register_js_bundle(self, name, *files): """Registers a JS bundle in the plugin's webassets environment""" pretty_name = re.sub(r'_js$', '', name) bundle = Bundle(*files, filters='rjsmin', output='js/{}_%(version)s.min.js'.format(pretty_name)) self.assets.register(name, bundle)
def _bundle_app_coffee(env, debug=False): """Compile the apps coffeescript and bundle it into appname.js""" COFFEE_PATH = 'coffee' APP_PATH = path.join(COFFEE_PATH, 'appname') scripts = ( path.join(COFFEE_PATH, 'nested.coffee'), path.join(COFFEE_PATH, 'app.coffee'), path.join(APP_PATH, 'app.coffee'), path.join(APP_PATH, 'menu.coffee'), path.join(APP_PATH, 'channel.coffee'), path.join(APP_PATH, 'contact.coffee'), path.join(APP_PATH, 'tag.coffee'), path.join(APP_PATH, 'person.coffee'), path.join(APP_PATH, 'vendor.coffee'), path.join(APP_PATH, 'activity.coffee'), path.join(APP_PATH, 'transaction.coffee'), path.join(APP_PATH, 'summary.coffee'), path.join(APP_PATH, 'router.coffee'), ) all_js = Bundle(*scripts, filters='coffeescript', output=path.join('..', 'static', 'script', 'appname.js')) env.add(all_js) if not debug: all_js.filters = 'closure_js'
def __init__(self, rh, templateClass): WPAdminPlugins.__init__(self, rh, 'livesync', '') self._templateClass = templateClass self._plugin_asset_env = PluginEnvironment('livesync', os.path.dirname(__file__), 'livesync') self._plugin_asset_env.register( 'livesync_js', Bundle('js/livesync.js', filters='rjsmin', output="livesync__%(version)s.min.js")) self._plugin_asset_env.register( 'livesync_css', Bundle('css/livesync.css', filters='cssmin', output="livesync__%(version)s.min.css"))
def get_assets_bottom_js_env(self, code_path, output_path): """ The directory structure of assets is: output_path static css js """ output_path = os.path.join(output_path, 'static') assets_env = Environment(output_path, '/static', debug=self.args.debug) assets_env.config['compass_config'] = { 'additional_import_paths': [os.path.join(code_path, 'scss-mixins')], #'sass_options': "cache: False", ??? i can't get it. 'http_path': "/static", } bottom_js_list = [] if "bottom_js" in self.config.data: bottom_js_list = self.config.data["bottom_js"] if bottom_js_list and len(bottom_js_list): bottom_js = Bundle(*bottom_js_list, filters='rjsmin', output='bottom.js') assets_env.register('bottom_js', bottom_js) return assets_env