Example #1
0
def webassets(ctx, debug=False, expire=True, replace=False):
    # Register our custom webassets filter.
    register_filter(ConsoleLogFilter)

    #--------------------------------------------------------------------------
    # Load webassets environment.
    env = YAMLLoader('./webassets.yaml').load_environment()
    env.debug = debug
    env.url_expire = expire

    #--------------------------------------------------------------------------
    # Generate css/js urls.
    css_urls = [env['external-css'], env['internal-css']]
    css_urls = [url_to_link(url) for urls in css_urls for url in urls.urls()]

    js_urls = [env['external-js'], env['internal-js']]
    js_urls = [url_to_script(url) for urls in js_urls for url in urls.urls()]

    print()
    print('* URLs css:')
    print(''.join((i.lstrip() for i in css_urls)))

    print('* URLs js:')
    print(''.join((i.lstrip() for i in js_urls)))

    if replace:
        sedplaceholder('wtee/templates/base.html', '<!-- WEBASSETS CSS -->',
                       css_urls)
        sedplaceholder('wtee/templates/base.html', '<!-- WEBASSETS JS -->',
                       js_urls)
Example #2
0
    def __init__(self,
                 path,
                 output,
                 static_path='static',
                 static_url='static',
                 asset_config='config.yml'):
        self.path = path
        self.output = output
        self.output_path = os.path.join(path, output)
        self.env = Environment(loader=FileSystemLoader(path),
                               extensions=[AssetsExtension])

        try:
            config_path = os.path.join(self.path, asset_config)
            asset_config = YAMLLoader(config_path)
            self.assets_env = asset_config.load_environment()
        except IOError:
            self.assets_env = AssetsEnvironment()

        if 'directory' not in self.assets_env.config:
            self.assets_env.directory = self.output_path

        if 'url' not in self.assets_env.config:
            self.assets_env.url = static_url

        self.assets_env.load_path = [self.path]
        self.env.assets_environment = self.assets_env
Example #3
0
    def __init__(self, paths=None,
                 packages=None,
                 assets_path=None,
                 globals=None,
                 overlay=None,
                 extensions=None,
                 env_template_params_key='pywb.template_params',
                 env_template_dir_key='pywb.templates_dir'):
        """Construct a new JinjaEnv.

        :param list[str] paths: List of paths to search for templates
        :param list[str] packages: List of assets package names
        :param str assets_path: Path to a yaml file containing assets
        :param dict[str, str] globals: Dictionary of additional globals available during template rendering
        :param overlay:
        :param list extensions: List of webassets extension classes
        :param str env_template_params_key: The full pywb package key for the template params
        :param str env_template_dir_key: The full pywb package key for the template directory
        """

        if paths is None:
            paths = ['templates', '.', '/']

        if packages is None:
            packages = ['pywb']

        self._init_filters()

        loader = ChoiceLoader(self._make_loaders(paths, packages))

        self.env_template_params_key = env_template_params_key
        self.env_template_dir_key = env_template_dir_key

        extensions = extensions or []

        if assets_path:
            extensions.append(AssetsExtension)

        if overlay:
            jinja_env = overlay.jinja_env.overlay(loader=loader,
                                                  trim_blocks=True,
                                                  extensions=extensions)
        else:
            jinja_env = RelEnvironment(loader=loader,
                                       trim_blocks=True,
                                       extensions=extensions)

        jinja_env.filters.update(self.filters)

        if globals:
            jinja_env.globals.update(globals)

        self.jinja_env = jinja_env

        # init assets
        if assets_path:
            assets_loader = YAMLLoader(load(assets_path))
            assets_env = assets_loader.load_environment()
            assets_env.resolver = PkgResResolver()
            jinja_env.assets_environment = assets_env
Example #4
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app, config_name)

    assets.init_app(app)
    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    assets_config = os.path.join(os.path.dirname(__file__), os.pardir,
                                 'webassets.yaml')
    assets._named_bundles = {}  # avoid duplicate registration in unit tests
    assets_loader = YAMLLoader(assets_config)
    bundles = assets_loader.load_bundles(assets)
    assets.register(bundles)

    if not app.debug and not app.testing and app.config[
            'SSL_STATUS'] == SSLStatus.ENABLED:
        sslify = SSLify(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    return app
Example #5
0
    def register_decanter_assets(self):
        path = os.path.join(DIR, 'assets', 'decanter.yaml')
        if not os.path.isfile(path):
            self._write_decanter_manifest(path)

        manifest = YAMLLoader(path)
        manifest = manifest.load_bundles()
        [self.register_asset_bundle(n, manifest[n]) for n in manifest]
Example #6
0
    def init_extensions(self):
        super(App, self).init_extensions()

        manifest = os.path.join(path, 'assets', 'manifest.yaml')
        bundles = YAMLLoader(manifest).load_bundles()

        for name, bundle in bundles.iteritems():
            self.assets.register(name, bundle)
Example #7
0
def build_if_needed(assets_path):
    env = YAMLLoader(assets_path).load_environment()
    env.resolver = PkgResResolver()

    for bundle in env:
        if env.updater.needs_rebuild(bundle, env):
            print('Updating {0}'.format(bundle.output))
            bundle.urls()
Example #8
0
def init_assets(app):
    app.assets = Environment(app)
    app.assets.auto_build = False
    app.assets.directory = os.path.join(DIR, 'assets')
    app.assets.manifest = 'file'
    app.assets.url = '/static'

    manifest = YAMLLoader(os.path.join(DIR, 'assets', 'manifest.yaml'))
    manifest = manifest.load_bundles()
    [app.assets.register(n, manifest[n]) for n in manifest]
Example #9
0
def init_assets(app):
    app.assets = Environment(app)
    app.assets.auto_build = False
    app.assets.directory = os.path.join(DIR, 'assets')
    app.assets.manifest = 'file'
    app.assets.url = '/static'

    manifest = YAMLLoader(os.path.join(DIR, 'assets', 'manifest.yaml'))
    manifest = manifest.load_bundles()
    [app.assets.register(n, manifest[n]) for n in manifest]
Example #10
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app, config_name)

    app.config['ASSETS_DEBUG'] = app.config['DEBUG']

    assets.init_app(app)
    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)

    assets_config = os.path.join(os.path.dirname(__file__), os.pardir, 'webassets.yaml')
    assets._named_bundles = {}  # avoid duplicate registration in unit tests
    assets_loader = YAMLLoader(assets_config)
    bundles = assets_loader.load_bundles(assets)
    assets.register(bundles)

    if not app.debug and not app.testing and app.config['SSL_STATUS'] == SSLStatus.ENABLED:
        sslify = SSLify(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    @app.context_processor
    def bokeh_resources():
        return dict(bokeh_resources=CDN)

    @app.cli.command()
    def flyway():
        # parse the database URI
        url = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
        jdbc_url = 'jdbc:{drivername}://{host}:{port}/{database}'.format(drivername=url.drivername,
                                                                         host=url.host,
                                                                         port=url.port if url.port else 3306,
                                                                         database=url.database)
        username = url.username
        password = url.password

        # get Flyway command to run
        settings = Config.settings(os.environ['FLASK_CONFIG'])
        args = [settings['flyway_command'],
                '-url=' + jdbc_url,
                '-user='******'-password='******'-locations=filesystem:' + settings['migration_sql_dir'],
                'migrate']

        return subprocess.call(args)

    return app
Example #11
0
def includeme(config):
    """pyramid include. declare the add_thumb_view"""
    here = os.path.dirname(__file__)
    settings = config.registry.settings

    config_dir = settings.get('garasu_webassets.config', '{}/configs'.format(here))
    LOG.debug(config_dir)
    # config_dir = AssetResolver(None).resolve(config_dir).abspath()
    asset_dir = settings.get('garasu_webassets.assets', '{}/assets'.format(here))
    LOG.debug(asset_dir)
    # asset_dir = AssetResolver(None).resolve(asset_dir).abspath()

    env = Environment(directory=asset_dir, url=settings['garasu_webassets.url'])
    env.manifest = settings['garasu_webassets.manifest']
    env.debug = asbool(settings['garasu_webassets.debug'])
    env.cache = asbool(settings['garasu_webassets.cache'])
    env.auto_build = asbool(settings['garasu_webassets.auto_build'])

    def text(value):
        if type(value) is six.binary_type:
            return value.decode('utf-8')
        else:
            return value

    def yaml_stream(fname, mode):
        if path.exists(fname):
            return open(fname, mode)
        raise FileNotFoundError

    fin = fileinput.input('/'.join([config_dir, settings['garasu_webassets.bundles']]),
                          openhook=yaml_stream)
    with closing(fin):
        lines = [text(line).rstrip() for line in fin]

    stream_yaml = six.StringIO('\n'.join(lines))
    loader = YAMLLoader(stream_yaml)
    result = loader.load_bundles()
    env.register(result)

    # for item in env:
    #     LOG.debug(item.output)
    #     path_file = '/'.join([public_dir, item.output])
    #     src_file = '/'.join([asset_dir, item.output])
    #     shutil.copy(src_file, path_file)

    def _get_assets(request, *args, **kwargs):
        bundle = Bundle(*args, **kwargs)
        with bundle.bind(env):
            urls = bundle.urls()
        return urls
    config.add_request_method(_get_assets, 'web_assets')

    def _get_assets_env(request):
        return env
    config.add_request_method(_get_assets_env, 'web_env', reify=True)
Example #12
0
    def load_bundles(self, bundle_file):
        """
        Load predefined bundles from a YAML file.

        See bundles.yaml for an example.
        """

        # Load bundles from YAML file
        loader = YAMLLoader(bundle_file)
        bundles = loader.load_bundles()

        # Register the bundles with the environment
        self.register(bundles)
Example #13
0
def configure_static_assets(app):

  loader = YAMLLoader('assets.yaml')
  assets = Environment(app)
  assets.manifest = None
  assets.cache = False
  assets.directory = './makers'
  assets.url = ''

  for name, bundle in loader.load_bundles().items():
    assets.register(name, bundle)

  app.environment = assets
Example #14
0
def setup_bundles(app):
    assets_env = Environment(app)
    assets_env.url = '/statics'
    assets_env.manifest = 'file:Compiled/static-manifest-version'
    assets_env.cache = False
    assets_env.auto_build = False
    assets_env.debug = app.config.get('DEVELOPMENT') == True

    # load and register bundles
    config_path = app.instance_path + '/config/asset_bundles.yaml'
    bundles = YAMLLoader(config_path).load_bundles()
    for name, bundle in bundles.iteritems():
       assets_env.register(name, bundle)

    app.assets_env = assets_env
 def reload_config(self):
     try:
         self.cmd.environment = YAMLLoader(
             self.ns.config).load_environment()
     except Exception as e:
         raise EnvironmentError(e)
     return True
Example #16
0
def init_app(app):
    here, f = os.path.split(os.path.abspath(__file__))

    # configure assets
    assets = Environment(app)
    assets.versions = 'hash'
    assets.directory = '%s/src' % here
    if app.debug == False:
        assets.auto_build = False

    # i have no idea why, but an arbitrary
    # second path segment is required here
    assets.url = '/static/turnip'

    # load asset bundles
    bundles = YAMLLoader("%s/src/assets.yaml" % here).load_bundles()
    [assets.register(name, bundle) for name, bundle in bundles.iteritems()]
Example #17
0
 def _setup_assets_env(self, ns, log):
     env = self.env
     if env is None:
         assert not (ns.module and ns.config)
         if ns.module:
             env = PythonLoader(ns.module).load_environment()
         if ns.config:
             env = YAMLLoader(ns.config).load_environment()
     return env
Example #18
0
    def __init__(self,
                 paths=['templates', '.', '/'],
                 packages=['pywb'],
                 assets_path=None,
                 globals=None,
                 overlay=None,
                 extensions=None,
                 env_template_params_key='pywb.template_params',
                 env_template_dir_key='pywb.templates_dir'):

        self._init_filters()

        loader = ChoiceLoader(self._make_loaders(paths, packages))

        self.env_template_params_key = env_template_params_key
        self.env_template_dir_key = env_template_dir_key

        extensions = extensions or []

        if assets_path:
            extensions.append(AssetsExtension)

        if overlay:
            jinja_env = overlay.jinja_env.overlay(loader=loader,
                                                  trim_blocks=True,
                                                  extensions=extensions)
        else:
            jinja_env = RelEnvironment(loader=loader,
                                       trim_blocks=True,
                                       extensions=extensions)

        jinja_env.filters.update(self.filters)

        if globals:
            jinja_env.globals.update(globals)

        self.jinja_env = jinja_env

        # init assets
        if assets_path:
            assets_loader = YAMLLoader(load(assets_path))
            assets_env = assets_loader.load_environment()
            assets_env.resolver = PkgResResolver()
            jinja_env.assets_environment = assets_env
Example #19
0
def get_webassets_env(conf):
    '''Get a preconfigured WebAssets environment'''
    # Configure webassets
    assets_environment = AssetsEnvironment(conf.get('static_files_dir', DEFAULT_STATIC), '/')
    assets_environment.debug = conf.get('debug', False)
    assets_environment.auto_build = conf.get('debug', False)
    assets_environment.config['less_paths'] = (
        'bower/bootstrap/less',
        'bower/etalab-assets/less',
        'bower/bootstrap-markdown/less',
    )

    # Load bundle from yaml file
    loader = YAMLLoader(resource_stream(__name__, '../assets.yaml'))
    bundles = loader.load_bundles()
    for name, bundle in bundles.items():
        assets_environment.register(name, bundle)

    return assets_environment
Example #20
0
def webassets(ctx, debug=False, expire=True, replace=False):
    # Register our custom webassets filter.
    register_filter(ConsoleLogFilter)

    #--------------------------------------------------------------------------
    # Copy fonts to webassets dir.
    print('* Copying fonts to %s' % ASSETDIR)
    fonts = [
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.eot',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.svg',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.ttf',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.woff',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.woff2',
    ]
    run('rsync -v {} {}'.format(' '.join(fonts), ASSETDIR / 'fonts'))

    #--------------------------------------------------------------------------
    # Load webassets environment.
    env = YAMLLoader('./webassets.yaml').load_environment()
    env.debug = debug
    env.url_expire = expire

    #--------------------------------------------------------------------------
    # Generate css/js urls.
    css_urls = [env['external-css'], env['selectize-css'], env['internal-css']]
    css_urls = [url_to_link(url) for urls in css_urls for url in urls.urls()]

    js_urls = [env['external-js'], env['internal-js']]
    js_urls = [url_to_script(url) for urls in js_urls for url in urls.urls()]

    print()
    print('* URLs css:')
    print(''.join((i.lstrip() for i in css_urls)))

    print('* URLs js:')
    print(''.join((i.lstrip() for i in js_urls)))

    if replace:
        sedplaceholder('tailon/templates/base.html', '<!-- WEBASSETS CSS -->',
                       css_urls)
        sedplaceholder('tailon/templates/base.html', '<!-- WEBASSETS JS -->',
                       js_urls)
Example #21
0
    def __init__(self, path, output, static_path="static", static_url="static", asset_config="config.yml"):
        self.path = path
        self.output = output
        self.output_path = os.path.join(path, output)
        self.env = Environment(loader=FileSystemLoader(path), extensions=[AssetsExtension])

        try:
            config_path = os.path.join(self.path, asset_config)
            asset_config = YAMLLoader(config_path)
            self.assets_env = asset_config.load_environment()
        except IOError:
            self.assets_env = AssetsEnvironment()

        if "directory" not in self.assets_env.config:
            self.assets_env.directory = self.output_path

        if "url" not in self.assets_env.config:
            self.assets_env.url = static_url

        self.assets_env.load_path = [self.path]
        self.env.assets_environment = self.assets_env
Example #22
0
def webassets(debug=False, expire=True, replace=False):
    # Register our custom webassets filter.
    register_filter(ConsoleLogFilter)

    #--------------------------------------------------------------------------
    # Copy fonts to webassets dir.
    print('* Copying fonts to %s' % ASSETDIR)
    fonts = [
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.eot',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.svg',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.ttf',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.woff',
        'tailon/assets/vendor/components-font-awesome/fonts/fontawesome-webfont.woff2',
    ]
    run('rsync -v {} {}'.format(' '.join(fonts), ASSETDIR / 'fonts'))

    #--------------------------------------------------------------------------
    # Load webassets environment.
    env = YAMLLoader('./webassets.yaml').load_environment()
    env.debug = debug
    env.url_expire = expire

    #--------------------------------------------------------------------------
    # Generate css/js urls.
    css_urls = [env['external-css'], env['selectize-css'], env['internal-css']]
    css_urls = [url_to_link(url) for urls in css_urls for url in urls.urls()]

    js_urls = [env['external-js'], env['internal-js']]
    js_urls = [url_to_script(url) for urls in js_urls for url in urls.urls()]

    print()
    print('* URLs css:')
    print(''.join((i.lstrip() for i in css_urls)))

    print('* URLs js:')
    print(''.join((i.lstrip() for i in js_urls)))

    if replace:
        sedplaceholder('tailon/templates/base.html', '<!-- WEBASSETS CSS -->', css_urls)
        sedplaceholder('tailon/templates/base.html', '<!-- WEBASSETS JS -->',  js_urls)
Example #23
0
    def __init__(self, paths=['templates', '.', '/'],
                       packages=['pywb'],
                       assets_path=None,
                       globals=None,
                       overlay=None,
                       extensions=None):

        self._init_filters()

        loader = ChoiceLoader(self._make_loaders(paths, packages))

        extensions = extensions or []

        if assets_path:
            extensions.append(AssetsExtension)

        if overlay:
            jinja_env = overlay.jinja_env.overlay(loader=loader,
                                                  trim_blocks=True,
                                                  extensions=extensions)
        else:
            jinja_env = RelEnvironment(loader=loader,
                                       trim_blocks=True,
                                       extensions=extensions)

        jinja_env.filters.update(self.filters)

        if globals:
            jinja_env.globals.update(globals)

        self.jinja_env = jinja_env

        # init assets
        if assets_path:
            assets_loader = YAMLLoader(assets_path)
            assets_env = assets_loader.load_environment()
            assets_env.resolver = PkgResResolver()
            jinja_env.assets_environment = assets_env
Example #24
0
def create_library(name, path):
    """Create WebAssets library(set of Bundles).
    """
    config_path = os.path.join(path, u'webassets.yml')
    if not os.path.exists(config_path):
        return

    library = YAMLLoader(config_path).load_bundles()
    bundles = {
        u'/'.join([name, key]): bundle
        for key, bundle in library.items()
    }

    # Unfortunately, you'll get an error attempting to register bundle
    # with the same name twice. For now, let's just pop existing
    # bundle and avoid name-conflicts
    # TODO: make PR into webassets with preferable solution
    # Issue: https://github.com/miracle2k/webassets/issues/519
    for name, bundle in bundles.items():
        env._named_bundles.pop(name, None)
        env.register(name, bundle)

    env.append_path(path)
Example #25
0
def get_webassets_env(base_dir, assets_url, debug=False):
    """
    Get a webassets environment configured for building browser extensions.

    :param base_dir: The directory into which the assets should be built.
    :param assets_url: The relative or absolute URL used to reference assets
                       in the app.html and embed.js files.
    :param debug: If true, generates source maps and skips minification.
    """
    webassets_env = webassets.Environment(
        directory=os.path.abspath(base_dir),
        url=assets_url)

    # Disable webassets caching and manifest generation
    webassets_env.cache = False
    webassets_env.manifest = False
    webassets_env.resolver = Resolver()
    webassets_env.config['UGLIFYJS_BIN'] = './node_modules/.bin/uglifyjs'
    webassets_env.debug = debug

    loader = YAMLLoader(resolve('h:assets.yaml').abspath())
    webassets_env.register(loader.load_bundles())

    return webassets_env
Example #26
0
def create_library(name, path):
    """Create WebAssets library(set of Bundles).
    """
    config_path = os.path.join(path, u'webassets.yml')
    if not os.path.exists(config_path):
        return

    library = YAMLLoader(config_path).load_bundles()
    bundles = {
        u'/'.join([name, key]): bundle
        for key, bundle
        in library.items()
    }

    # Unfortunately, you'll get an error attempting to register bundle
    # with the same name twice. For now, let's just pop existing
    # bundle and avoid name-conflicts
    # TODO: make PR into webassets with preferable solution
    # Issue: https://github.com/miracle2k/webassets/issues/519
    for name, bundle in bundles.items():
        env._named_bundles.pop(name, None)
        env.register(name, bundle)

    env.append_path(path)
Example #27
0
    def run_with_argv(self, argv):
        try:
            ns = self.parser.parse_args(argv)
        except SystemExit:
            # We do not want the main() function to exit the program.
            # See run() instead.
            return 1

        # Setup logging
        if self.log:
            log = self.log
        else:
            log = logging.getLogger('webassets')
            log.setLevel(logging.DEBUG if ns.verbose else (
                logging.WARNING if ns.quiet else logging.INFO))
            log.addHandler(logging.StreamHandler())

        # Load the bundles we shall work with
        env = self.env
        if env is None:
            assert not (ns.module and ns.config)
            if ns.module:
                env = PythonLoader(ns.module).load_environment()
            if ns.config:
                env = YAMLLoader(ns.config).load_environment()

        if env is None:
            raise CommandError(
                "Error: No environment given or found. Maybe use -m?")

        # Prepare a dict of arguments cleaned of values that are not
        # command-specific, and which the command method would not accept.
        args = vars(ns).copy()
        for name in ('verbose', 'quiet', 'module', 'config', 'command'):
            if name in args:
                del args[name]

        # Run the selected command
        cmd = CommandLineEnvironment(env, log)
        return cmd.invoke(ns.command, args)
Example #28
0
__author__ = 'hsk81'

###############################################################################
###############################################################################

from flask.ext.assets import Environment
from webassets.loaders import YAMLLoader

from ..app import app

###############################################################################
###############################################################################

loader = YAMLLoader (app.config['YML_FILE'])
bundles = loader.load_bundles ()

assets = Environment (app)
assets.manifest = 'cache'
assets.register (bundles)
assets.url = app.config.get ('CDN')

###############################################################################
###############################################################################
Example #29
0
def create_app(version_path, secret_key, session_cookie_name,
               session_cookie_domain, session_cookie_secure, use_https,
               enable_asset_pipeline, lando_api_url):
    """
    Create an app instance.
    """
    csp = {
        'default-src': "'self'",
        'font-src': "'self' https://code.cdn.mozilla.net",
        'style-src': "'self' https://code.cdn.mozilla.net",
        'img-src': "'self' *.cloudfront.net *.gravatar.com "
                   "*.googleusercontent.com",
        'object-src': "'none'",
        'frame-ancestors': "'none'",
        'manifest-src': "'none'",
        'worker-src': "'none'",
        'media-src': "'none'",
        'frame-src': "'none'",
        'base-uri': "'none'",
        'report-uri': "/__cspreport__"
    }  # yapf: disable

    initialize_logging()

    app = Flask(__name__)

    # Set configuration
    app.config['VERSION_PATH'] = version_path
    log_config_change('VERSION_PATH', version_path)

    version_info = json.load(open(version_path))
    logger.info(version_info, 'app.version')

    this_app_version = version_info['version']
    initialize_sentry(app, this_app_version)

    app.config['LANDO_API_URL'] = lando_api_url
    log_config_change('LANDO_API_URL', lando_api_url)

    # Set remaining configuration
    app.config['SECRET_KEY'] = secret_key
    app.config['SESSION_COOKIE_NAME'] = session_cookie_name
    app.config['SESSION_COOKIE_DOMAIN'] = session_cookie_domain
    app.config['SESSION_COOKIE_SECURE'] = session_cookie_secure
    app.config['SERVER_NAME'] = session_cookie_domain
    app.config['USE_HTTPS'] = use_https
    app.config['PREFERRED_URL_SCHEME'] = 'https' if use_https else 'http'

    Talisman(app, content_security_policy=csp, force_https=use_https)

    # Authentication
    global oidc
    authentication = auth.OpenIDConnect(auth.OIDCConfig())
    oidc = authentication.auth(app)

    # Register routes via Flask Blueprints
    from landoui.pages import pages
    from landoui.revisions import revisions
    from landoui.dockerflow import dockerflow
    app.register_blueprint(pages)
    app.register_blueprint(revisions)
    app.register_blueprint(dockerflow)

    # Register template helpers
    from landoui.template_helpers import template_helpers
    app.register_blueprint(template_helpers)

    # Register error pages
    errorhandlers.register_error_handlers(app)

    # Setup Flask Assets
    assets = Environment(app)
    if enable_asset_pipeline:
        loader = YAMLLoader(
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         'assets_src/assets.yml'))
        assets.register(loader.load_bundles())

    return app
Example #30
0
 def from_yaml(self, path):
     """Register bundles from a YAML configuration file"""
     bundles = YAMLLoader(path).load_bundles()
     [self.register(name, bundle) for name, bundle in bundles.iteritems()]
Example #31
0
except IOError:
    pass


if os.getenv('SPAMSUB_CONFIGURATION'):
    app.config.from_envvar('SPAMSUB_CONFIGURATION')

# attach assets
assets = Environment(app)
assets.versions = 'hash'

manifest_path = os.path.realpath(
    os.path.join(os.path.dirname(__file__), '.static-manifest'))
assets.manifest = 'file://%s' % manifest_path

bundles = YAMLLoader(os.path.realpath(
    os.path.join(os.path.dirname(__file__), 'assets.yml'))).load_bundles()

for bundle_name, bundle in bundles.items():
    assets.register(bundle_name, bundle)

## import our own blueprints here if necessary
# from apps.foo.views import foo_app
# attach any blueprints
# app.register_blueprint(foo_app, url_prefix='/foo')


# Error handling
@app.errorhandler(404)
def page_not_found(error):
    """ 404 handler """
    return render_template(
Example #32
0
    def __init__(self,
                 config_dir=None,
                 app_config=None,
                 logging_config=None,
                 webassets_env=None,
                 environment=None,
                 env_var_name='BLUEBERRYPY_CONFIG'):
        """Loads BlueberryPy configuration from `config_dir` if supplied.

        If `app_config` or `logging_config` or `webassets_env` are given, they
        will be used instead of the configuration files found from `config_dir`.

        If `environment` is given, it must be an existing CherryPy environment.
        If `environment` is `production`, and `config_dir` is given, the `prod`
        subdirectory will be searched for configuration files, otherwise the
        `dev` subdirectory` will be searched.

        If `env_var_name` is given, it must be an existing environment
        variable, it will override values from YAML config.

        Upon initialization of this configuration object, all the configuration
        will be validated for sanity and either BlueberryPyConfigurationError or
        BlueberryPyNotConfiguredError will be thrown if insane. For less severe
        configuration insanity cases, a warning will be emitted instead.

        :arg config_dir: a path, str
        :arg app_config: a CherryPy config, dict
        :arg logging_config: a logging config, dict
        :arg webassets_env: a webassets environment, webassets.Environment
        :arg environment: a CherryPy configuration environment, str
        :arg env_var_name: an environment variable name for configuration, str
        """

        ENV_CONFIG = self.__class__._load_env_var(env_var_name)

        CWD = os.getcwdu() if getattr(os, "getcwdu", None) else os.getcwd()

        if ENV_CONFIG.get('global', {}).get('CWD') and \
                os.path.isdir(
                    os.path.join(ENV_CONFIG['global']['CWD'], 'src')):
            CWD = ENV_CONFIG['global']['CWD']

        if config_dir is None:
            self.config_dir = config_dir = os.path.join(CWD, "config")
        else:
            self.config_dir = config_dir = os.path.abspath(config_dir)

        if environment == "production":
            self.config_dir = config_dir = os.path.join(config_dir, "prod")
        elif environment == "test_suite" and os.path.exists(
                os.path.join(config_dir, "test")):
            self.config_dir = config_dir = os.path.join(config_dir, "test")
        else:
            self.config_dir = config_dir = os.path.join(config_dir, "dev")

        config_file_paths = {}
        app_yml_path = os.path.join(config_dir, "app.yml")
        logging_yml_path = os.path.join(config_dir, "logging.yml")
        bundles_yml_path = os.path.join(config_dir, "bundles.yml")

        # A local-only config, which overrides the app.yml values
        app_override_yml_path = os.path.join(config_dir, "app.override.yml")

        if os.path.exists(app_yml_path):
            config_file_paths["app_yml"] = app_yml_path

        if os.path.exists(logging_yml_path):
            config_file_paths["logging_yml"] = logging_yml_path

        if os.path.exists(bundles_yml_path):
            config_file_paths["bundles_yml"] = bundles_yml_path

        if os.path.exists(app_override_yml_path):
            config_file_paths["app_override_yml"] = app_override_yml_path

        self._config_file_paths = config_file_paths

        if "app_yml" in config_file_paths and not app_config:
            with open(config_file_paths["app_yml"]) as app_yml:
                self._app_config = load(app_yml, self._YAMLLoader)

            # If the overrides file exists, override the app config values
            # with ones from app.override.yml
            if "app_override_yml" in config_file_paths:
                app_override_config = {}
                with open(config_file_paths["app_override_yml"]
                          ) as app_override_yml:
                    app_override_config = load(app_override_yml,
                                               self._YAMLLoader)

                self._app_config = self.__class__.merge_dicts(
                    self._app_config, app_override_config)

        if "logging_yml" in config_file_paths and not logging_config:
            with open(config_file_paths["logging_yml"]) as logging_yml:
                self._logging_config = load(logging_yml, self._YAMLLoader)

        if "bundles_yml" in config_file_paths and not webassets_env:
            from webassets.loaders import YAMLLoader
            self._webassets_env = YAMLLoader(
                config_file_paths["bundles_yml"]).load_environment()

        if app_config:
            self._app_config = dict(app_config)

        try:
            # Merge JSON from environment variable
            self._app_config = self.__class__.merge_dicts(
                self._app_config, ENV_CONFIG)
        except AttributeError:
            if ENV_CONFIG:  # not an empty dict
                self._app_config = ENV_CONFIG
            # Don't re-raise exception, self.validate() will do this later

        if logging_config:
            self._logging_config = dict(logging_config)

        if webassets_env is not None:
            self._webassets_env = webassets_env

        self.validate()  # Checks that all attributes are pre-populated

        # Convert relative paths to absolute where needed
        # self.validate() will fail if there's no app_config['controllers']
        for _ in self._app_config['controllers']:
            section = self._app_config['controllers'][_]
            for r in section:
                if isinstance(section[r], dict):
                    for __ in [
                            'tools.staticdir.root', 'tools.staticfile.root'
                    ]:
                        pth = section[r].get(__)
                        if pth is not None and not pth.startswith('/'):
                            self._app_config['controllers'][_][r][__] = \
                                os.path.join(CWD, pth)

        # Convert relative paths of logs in handlers
        # self.validate() will fail if there's no self._logging_config
        for handler_name, handler_config in (getattr(
                self, '_logging_config', {}) or {}).get('handlers',
                                                        {}).viewitems():
            pth = handler_config.get('filename')
            if pth is not None and not pth.startswith('/'):
                self._logging_config['handlers'][handler_name]['filename'] = \
                    os.path.join(CWD, pth)

        if environment == "backlash":
            self.setup_backlash_environment()
Example #33
0
from webassets.loaders import YAMLLoader

loader = YAMLLoader("source/_static/assets.yml")
env = loader.load_environment()

print "Building assets.."

js_assets = env["scripts"].urls()
css_assets = env["styles"].urls()

js_assets_rel = []
for asset in js_assets:
    print " - {}".format(asset)
    asset = "_static{}".format(asset)
    js_assets_rel.append(asset)

css_assets_rel = []
for asset in css_assets:
    print " - {}".format(asset)
    asset = asset[1:]
    css_assets_rel.append(asset)

js = "{{% set script_files = ['{}'] %}}\n".format("', '".join(js_assets_rel))
css = "{{% set css_files = ['{}'] %}}\n".format("', '".join(css_assets_rel))

fp = open("source/_static/assets/assets.html", mode="w")
fp.writelines([js, css])
fp.close()

print "done"
Example #34
0
def make_app(env="dev"):
    """
    This is still needlessly complicated.

    Returns a Flask WSGI instance.
    """
    debug = env == "dev"

    url_root = dict(
        dev="/",
        build="/dist/",
        test="/dist/",
        prod="/"
    )[env]

    app_home = os.path.dirname(__file__)

    cfg = dict(
        dev=dict(
            static_url_path="/static",
            template_folder="./templates",
            static_folder=opa(opj(app_home, "static"))
        ),
        build=dict(
            static_url_path="/",
            template_folder="./templates",
            static_folder=opa(opj(app_home, "static"))
        ),
        test=dict(
            static_url_path="/dist",
            template_folder="../dist",
            static_folder=opa(opj(app_home, "..", "dist"))
        ),
        prod=dict(
            static_url_path="/static",
            template_folder="./templates",
            static_folder=opa(opj(app_home, "static"))
        )
    )[env]

    app = Flask(__name__, **cfg)

    app.config.update(dict(
        CSRF_ENABLED=debug,
        SECRET_KEY=os.environ.get("FLASK_SECRET_KEY", "totally-insecure"),
        DEBUG=debug,
        ASSETS_DEBUG=debug,
        BOOTSTRAP_JQUERY_VERSION=None
    ))

    Bootstrap(app)

    def font_stuff(url):
        """
        Some font URL rewriting
        """
        repl = "./lib/awesome/font/"
        if env == "build":
            repl = "./font/"
        return url.replace("../font/", repl)

    fix_font_css = CSSRewrite(replace=font_stuff)

    assets = Environment(app)

    bundles = YAMLLoader(os.path.join(app_home, 'assets.yaml')).load_bundles()

    for to_fix in ["prod", "build"]:
        bundles["css-%s" % to_fix].filters.insert(0, fix_font_css)

    for name, bundle in bundles.iteritems():
        assets.register(name, bundle)


    @app.route(url_root)
    def index():
        kwargs = {
            "gh_client_id": os.environ.get("GITHUB_CLIENT_ID", 
                "deadbeef")
        }

        return render_template("index.html", env=env, **kwargs)


    @app.route("/login")
    def login(code=None):
        return render_template("login.html")


    @app.route("/oauth")
    def oauth():
        oauth_args = dict(
            code=request.args.get("code", ""),
            state=request.args.get("state", ""),
            client_id=os.environ["GITHUB_CLIENT_ID"],
            client_secret=os.environ["GITHUB_CLIENT_SECRET"]
        )
        
        req = requests.post(
            "https://github.com/login/oauth/access_token",
            data=oauth_args
        )
        
        query = urlparse.parse_qs(req.content)
        
        return query["access_token"][0]

    return app
Example #35
0
    def __init__(self,
                 paths=None,
                 packages=None,
                 assets_path=None,
                 globals=None,
                 overlay=None,
                 extensions=None,
                 env_template_params_key='pywb.template_params',
                 env_template_dir_key='pywb.templates_dir'):
        """Construct a new JinjaEnv.

        :param list[str] paths: List of paths to search for templates
        :param list[str] packages: List of assets package names
        :param str assets_path: Path to a yaml file containing assets
        :param dict[str, str] globals: Dictionary of additional globals available during template rendering
        :param overlay:
        :param list extensions: List of webassets extension classes
        :param str env_template_params_key: The full pywb package key for the template params
        :param str env_template_dir_key: The full pywb package key for the template directory
        """

        if paths is None:
            paths = ['templates', '.', '/']

        if packages is None:
            packages = ['pywb']

        self._init_filters()

        loader = ChoiceLoader(self._make_loaders(paths, packages))

        self.env_template_params_key = env_template_params_key
        self.env_template_dir_key = env_template_dir_key

        extensions = extensions or []

        if assets_path:
            extensions.append(AssetsExtension)

        if overlay:
            jinja_env = overlay.jinja_env.overlay(
                loader=loader,
                autoescape=select_autoescape(),
                trim_blocks=True,
                extensions=extensions)
        else:
            jinja_env = RelEnvironment(loader=loader,
                                       autoescape=select_autoescape(),
                                       trim_blocks=True,
                                       extensions=extensions)

        jinja_env.filters.update(self.filters)

        if globals:
            jinja_env.globals.update(globals)

        self.jinja_env = jinja_env

        # init assets
        if assets_path:
            assets_loader = YAMLLoader(load(assets_path))
            assets_env = assets_loader.load_environment()
            assets_env.resolver = PkgResResolver()
            jinja_env.assets_environment = assets_env

        self.default_locale = ''
Example #36
0
def get_webassets_env_from_settings(settings, prefix='webassets'):
    """This function will take all webassets.* parameters, and
    call the ``Environment()`` constructor with kwargs passed in.

    The only two parameters that are not passed as keywords are:

    * base_dir
    * base_url

    which are passed in positionally.

    Read the ``WebAssets`` docs for ``Environment`` for more details.
    """
    # Make a dictionary of the webassets.* elements...
    kwargs = {}   # assets settings
    cut_prefix = len(prefix) + 1
    for k in settings:
        if k.startswith(prefix):
            val = settings[k]
            if isinstance(val, six.string_types):
                if val.lower() in auto_booly:
                    val = asbool(val)
                elif val.lower().startswith('json:') and k[cut_prefix:] != 'manifest':
                    val = json.loads(val[5:])
            kwargs[k[cut_prefix:]] = val

    if 'base_dir' not in kwargs:
        raise Exception("You need to provide webassets.base_dir in your configuration")
    if 'base_url' not in kwargs:
        raise Exception("You need to provide webassets.base_url in your configuration")

    asset_dir = kwargs.pop('base_dir')
    asset_url = kwargs.pop('base_url')

    if ':' in asset_dir:
        try:
            asset_dir = AssetResolver(None).resolve(asset_dir).abspath()
        except ImportError:
            pass

    if 'debug' in kwargs:
        kwargs['debug'] = maybebool(kwargs['debug'])

    if 'cache' in kwargs:
        cache = kwargs['cache'] = maybebool(kwargs['cache'])

        if cache and isinstance(cache, six.string_types) and not path.isdir(cache):
            makedirs(cache)

    # 'updater' is just passed in...

    if 'auto_build' in kwargs:
        kwargs['auto_build'] = maybebool(kwargs['auto_build'])

    if 'jst_compiler' in kwargs:
        kwargs['JST_COMPILER'] = kwargs.pop('jst_compiler')

    if 'jst_namespace' in kwargs:
        kwargs['JST_NAMESPACE'] = kwargs.pop('jst_namespace')

    if 'manifest' in kwargs:
        kwargs['manifest'] = maybebool(kwargs['manifest'])

    if 'url_expire' in kwargs:
        kwargs['url_expire'] = maybebool(kwargs['url_expire'])

    if 'static_view' in kwargs:
        kwargs['static_view'] = asbool(kwargs['static_view'])
    else:
        kwargs['static_view'] = False

    if 'cache_max_age' in kwargs:
        kwargs['cache_max_age'] = int(kwargs.pop('cache_max_age'))
    else:
        kwargs['cache_max_age'] = None

    if 'load_path' in kwargs:
        # force load_path to be an array and split on whitespace
        if not isinstance(kwargs['load_path'], list):
            kwargs['load_path'] = kwargs['load_path'].split()

    paths = kwargs.pop('paths', None)

    if 'bundles' in kwargs:
        if isinstance(kwargs['bundles'], six.string_types):
            kwargs['bundles'] = kwargs['bundles'].split()

    bundles = kwargs.pop('bundles', None)

    assets_env = Environment(asset_dir, asset_url, **kwargs)

    if paths is not None:
        for map_path, map_url in json.loads(paths).items():
            assets_env.append_path(map_path, map_url)

    def yaml_stream(fname):
        if path.exists(fname):
            return open(fname, 'rb')
        else:
            return assets_env.resolver.resolver.resolve(fname).stream()

    if isinstance(bundles, list):
        loaded = {}
        for bpath in reversed(bundles):
            with closing(yaml_stream(bpath)) as s:
                loader = YAMLLoader(s)
                loaded.update(loader.load_bundles())
        assets_env.register(loaded)
    elif isinstance(bundles, dict):
        assets_env.register(bundles)

    return assets_env
Example #37
0
def create_app(ENV_SETTING):
    app = Flask(__name__, instance_relative_config=True)

    #configuration
    app.config.from_object(app_config[ENV_SETTING])

    # Logging configuration
    logging.config.dictConfig(yaml.load(open(app.config['LOGGING_FILEPATH'])))

    # Yaml Loader to load css and js
    assets = Environment(app)
    loader = YAMLLoader(app.config['ASSETS_FILEPATH']).load_bundles()
    load_assets(assets, loader)

    #database init
    db.init_app(app)
    # with app.app_context():
    #     create_user(app,db)
    #flask_admin
    admin = Admin(app, index_view=AdminIndexCustomView(url=None,endpoint=None) , name='Admin Panel', base_template='admin/my_master.html', template_mode='bootstrap3')
    # Mail
    mail.init_app(app)
    # csrf
    csrf.init_app(app)
    #SSL
    sslify = SSLify(app)
    #setting babelex
    babel = Babel(app)
    @babel.localeselector
    def get_locale():
        # if the user has set up the language manually it will be stored in the session,
        # so we use the locale from the user settings
        try:
            language = session['language']
        except KeyError:
            language = None
        if language is not None:
            return language
        return request.accept_languages.best_match(app.config['LANGUAGES'].keys())

    # Inject to JINJA Template
    app.context_processor(inject_current_language)
    app.context_processor(inject_all_languages)
    app.context_processor(inject_google_token)
    app.context_processor(inject_total_notification)
    app.context_processor(inject_tasks)

    # Template Filter
    app.jinja_env.globals['momentjs'] = momentjs

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    # Integrate Flask Security with Flask Admin
    @security.context_processor
    def security_context_processor():
        return dict(
            admin_base_template=admin.base_template,
            admin_view=admin.index_view,
            h=admin_helpers,
            get_url=url_for
        )

    # Admin Views
    load_admin_views(admin, db)
    # Blueprint Views
    load_blueprints(app)
    # Register Error Handling
    app.register_error_handler(400, bad_request)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(403, page_forbidden)
    app.register_error_handler(500, page_server_error)
    app.logger.info('app started')

    return app
Example #38
0
def add_webassets(config):
    loader = YAMLLoader(join(dirname(__file__), 'resources.yaml'))
    bundles = loader.load_bundles()
    for name in bundles:
        config.add_webasset(name, bundles[name])
Example #39
0
    def __init__(self,
                 config_dir=None,
                 app_config=None,
                 logging_config=None,
                 webassets_env=None,
                 environment=None):
        """Loads BlueberryPy configuration from `config_dir` if supplied.

        If `app_config` or `logging_config` or `webassets_env` are given, they
        will be used instead of the configuration files found from `config_dir`.

        If `environment` is given, it must be an existing CherryPy environment.
        If `environment` is `production`, and `config_dir` is given, the `prod`
        subdirectory will be searched for configuration files, otherwise the
        `dev` subdirectory` will be searched.

        Upon initialization of this configuration object, all the configuration
        will be validated for sanity and either BlueberryPyConfigurationError or
        BlueberryPyNotConfiguredError will be thrown if insane. For less severe
        configuration insanity cases, a warning will be emitted instead.

        :arg config_dir: a path, str
        :arg app_config: a CherryPy config, dict
        :arg logging_config: a logging config, dict
        :arg webassets_env: a webassets environment, webassets.Environment
        :arg environment: a CherryPy configuration environment, str
        """

        if config_dir is None:
            self.config_dir = config_dir = os.path.join(os.getcwdu(), "config")
        else:
            self.config_dir = config_dir = os.path.abspath(config_dir)

        if environment == "production":
            self.config_dir = config_dir = os.path.join(config_dir, "prod")
        elif environment == "test_suite" and os.path.exists(
                os.path.join(config_dir, "test")):
            self.config_dir = config_dir = os.path.join(config_dir, "test")
        else:
            self.config_dir = config_dir = os.path.join(config_dir, "dev")

        config_file_paths = {}
        app_yml_path = os.path.join(config_dir, "app.yml")
        logging_yml_path = os.path.join(config_dir, "logging.yml")
        bundles_yml_path = os.path.join(config_dir, "bundles.yml")

        if os.path.exists(app_yml_path):
            config_file_paths["app_yml"] = app_yml_path

        if os.path.exists(logging_yml_path):
            config_file_paths["logging_yml"] = logging_yml_path

        if os.path.exists(bundles_yml_path):
            config_file_paths["bundles_yml"] = bundles_yml_path

        self._config_file_paths = config_file_paths

        if "app_yml" in config_file_paths and not app_config:
            with open(config_file_paths["app_yml"]) as app_yml:
                self._app_config = load(app_yml, Loader)

        if "logging_yml" in config_file_paths and not logging_config:
            with open(config_file_paths["logging_yml"]) as logging_yml:
                self._logging_config = load(logging_yml, Loader)

        if "bundles_yml" in config_file_paths and not webassets_env:
            from webassets.loaders import YAMLLoader
            self._webassets_env = YAMLLoader(
                config_file_paths["bundles_yml"]).load_environment()

        if app_config:
            self._app_config = dict(app_config)

        if logging_config:
            self._logging_config = dict(logging_config)

        if webassets_env is not None:
            self._webassets_env = webassets_env

        self.validate()

        if environment == "backlash":
            self.setup_backlash_environment()
Example #40
0
db.init_app(app)

# load configs
app.config.from_pyfile('config/default.cfg')
# dev config will override anything set on line above
if os.getenv('DEV_CONFIGURATION'):
    app.config.from_envvar('DEV_CONFIGURATION')

# attach assets
assets = Environment(app)
assets.versions = 'hash'
assets.url = app.static_url_path
manifest_path = os.path.realpath(
    os.path.join(os.path.dirname(__file__), '.static-manifest'))
assets.manifest = 'file://%s' % manifest_path
bundles = YAMLLoader(os.path.realpath(
    os.path.join(os.path.dirname(__file__), 'assets.yml'))).load_bundles()
for bundle_name, bundle in bundles.items():
    assets.register(bundle_name, bundle)

# set up logging
if not app.debug:
    log_format = logging.Formatter("""
---
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Time:               %(asctime)s

%(message)s

""")
Example #41
0
env = os.environ.get('FLASK_ENV', 'development').lower()

app = Flask(__name__, static_folder='static')

if env == 'development':
    app.config.from_object('config.DevelopmentConfig')
    from flask_debugtoolbar import DebugToolbarExtension
    DebugToolbarExtension(app)
elif env == 'production':
    app.config.from_object('config.ProductionConfig')

# Setup database
db = SQLAlchemy(app)

# Setup login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'auth.login'

# Setup assets
assets_env = Environment(app)
yaml_loader = YAMLLoader(current_dir + '/assets.yml')
for name, bundle in yaml_loader.load_bundles().iteritems():
    assets_env.register(name, bundle)

# Registering blueprints:
from antiques.core.views import *  # noqa
from antiques.auth.views import auth_module  # noqa

app.register_blueprint(auth_module, url_prefix='/auth')
Example #42
0
 def register_assets(self):
     manifest = YAMLLoader(os.path.join(self.project_root,
                                        'assets',
                                        'manifest.yaml'))
     manifest = manifest.load_bundles()
     [self.register_asset_bundle(n, manifest[n]) for n in manifest]
Example #43
0
def get_webassets_env_from_settings(settings, prefix='webassets'):
    """This function will take all webassets.* parameters, and
    call the ``Environment()`` constructor with kwargs passed in.

    The only two parameters that are not passed as keywords are:

    * base_dir
    * base_url

    which are passed in positionally.

    Read the ``WebAssets`` docs for ``Environment`` for more details.
    """
    # Make a dictionary of the webassets.* elements...
    kwargs = {}   # assets settings
    cut_prefix = len(prefix) + 1
    for k in settings:
        if k.startswith(prefix):
            val = settings[k]
            if isinstance(val, six.string_types):
                if val.lower() in auto_booly:
                    val = asbool(val)
                elif val.lower().startswith('json:') and k[cut_prefix:] != 'manifest':
                    val = json.loads(val[5:])
            kwargs[k[cut_prefix:]] = val

    if 'base_dir' not in kwargs:
        raise Exception("You need to provide webassets.base_dir in your configuration")
    if 'base_url' not in kwargs:
        raise Exception("You need to provide webassets.base_url in your configuration")

    asset_dir = kwargs.pop('base_dir')
    asset_url = kwargs.pop('base_url')

    if ':' in asset_dir:
        try:
            asset_dir = AssetResolver(None).resolve(asset_dir).abspath()
        except ImportError:
            pass

    if 'debug' in kwargs:
        kwargs['debug'] = maybebool(kwargs['debug'])

    if 'cache' in kwargs:
        cache = kwargs['cache'] = maybebool(kwargs['cache'])

        if cache and isinstance(cache, six.string_types) and not path.isdir(cache):
            makedirs(cache)

    # 'updater' is just passed in...

    if 'auto_build' in kwargs:
        kwargs['auto_build'] = maybebool(kwargs['auto_build'])

    if 'jst_compiler' in kwargs:
        kwargs['JST_COMPILER'] = kwargs.pop('jst_compiler')

    if 'jst_namespace' in kwargs:
        kwargs['JST_NAMESPACE'] = kwargs.pop('jst_namespace')

    if 'manifest' in kwargs:
        kwargs['manifest'] = maybebool(kwargs['manifest'])

    if 'url_expire' in kwargs:
        kwargs['url_expire'] = maybebool(kwargs['url_expire'])

    if 'static_view' in kwargs:
        kwargs['static_view'] = asbool(kwargs['static_view'])
    else:
        kwargs['static_view'] = False

    if 'cache_max_age' in kwargs:
        kwargs['cache_max_age'] = int(kwargs.pop('cache_max_age'))
    else:
        kwargs['cache_max_age'] = None

    if 'load_path' in kwargs:
        # force load_path to be an array and split on whitespace
        if not isinstance(kwargs['load_path'], list):
            kwargs['load_path'] = kwargs['load_path'].split()

    paths = kwargs.pop('paths', None)

    if 'bundles' in kwargs:
        if isinstance(kwargs['bundles'], six.string_types):
            kwargs['bundles'] = kwargs['bundles'].split()

    bundles = kwargs.pop('bundles', None)

    assets_env = Environment(asset_dir, asset_url, **kwargs)

    if paths is not None:
        for map_path, map_url in json.loads(paths).items():
            assets_env.append_path(map_path, map_url)

    def yaml_stream(fname):
        if path.exists(fname):
            return open(fname, 'rb')
        else:
            return assets_env.resolver.resolver.resolve(fname).stream()

    if isinstance(bundles, list):
        loaded = {}
        for bpath in bundles:
            with closing(yaml_stream(bpath)) as s:
                loader = YAMLLoader(s)
                loaded.update(loader.load_bundles())
        assets_env.register(loaded)
    elif isinstance(bundles, dict):
        assets_env.register(bundles)

    return assets_env
Example #44
0
def create_app(
    version_path,
    secret_key,
    session_cookie_name,
    session_cookie_domain,
    session_cookie_secure,
    use_https,
    enable_asset_pipeline,
    lando_api_url,
    debug=False,
):
    """
    Create an app instance.
    """
    csp = {
        "default-src": "'self'",
        "font-src": "'self' https://code.cdn.mozilla.net",
        "style-src": "'self' https://code.cdn.mozilla.net",
        "img-src": "'self' *.cloudfront.net *.gravatar.com " "*.googleusercontent.com",
        "object-src": "'none'",
        "frame-ancestors": "'none'",
        "manifest-src": "'none'",
        "worker-src": "'none'",
        "media-src": "'none'",
        "frame-src": "'none'",
        "base-uri": "'none'",
        "report-uri": "/__cspreport__",
    }  # yapf: disable

    initialize_logging()

    app = Flask(__name__)
    app.debug = debug

    # Set configuration
    version_info = get_app_version(version_path)
    logger.info("application version", extra=version_info)
    initialize_sentry(app, version_info["version"])

    set_config_param(app, "LANDO_API_URL", lando_api_url)
    set_config_param(app, "BUGZILLA_URL",
                     _lookup_service_url(lando_api_url, "bugzilla"))
    set_config_param(app, "PHABRICATOR_URL",
                     _lookup_service_url(lando_api_url, "phabricator"))
    set_config_param(app, "SECRET_KEY", secret_key, obfuscate=True)
    set_config_param(app, "SESSION_COOKIE_NAME", session_cookie_name)
    set_config_param(app, "SESSION_COOKIE_DOMAIN", session_cookie_domain)
    set_config_param(app, "SESSION_COOKIE_SECURE", session_cookie_secure)
    set_config_param(app, "SERVER_NAME", session_cookie_domain)
    set_config_param(app, "USE_HTTPS", use_https)

    app.config["PREFERRED_URL_SCHEME"] = "https" if use_https else "http"
    app.config["VERSION"] = version_info

    # Flags that need to be deprecated in the future.
    set_config_param(app, "ENABLE_SEC_APPROVAL",
                     bool(os.getenv("ENABLE_SEC_APPROVAL")))

    set_config_param(
        app,
        "ENABLE_EMBEDDED_TRANSPLANT_UI",
        bool(os.getenv("ENABLE_EMBEDDED_TRANSPLANT_UI")),
    )

    Talisman(app, content_security_policy=csp, force_https=use_https)

    # Authentication
    global oidc
    authentication = auth.OpenIDConnect(auth.OIDCConfig())
    oidc = authentication.auth(app)

    # Register routes via Flask Blueprints
    from landoui.pages import pages
    from landoui.revisions import revisions
    from landoui.dockerflow import dockerflow

    app.register_blueprint(pages)
    app.register_blueprint(revisions)
    app.register_blueprint(dockerflow)

    # Register template helpers
    from landoui.template_helpers import template_helpers

    app.register_blueprint(template_helpers)

    # Register error pages
    errorhandlers.register_error_handlers(app)

    # Setup Flask Assets
    assets = Environment(app)
    if enable_asset_pipeline:
        loader = YAMLLoader(
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "assets_src/assets.yml"))
        assets.register(loader.load_bundles())

    logger.info("Application started successfully.")
    return app
Example #45
0
app.config['SQLALCHEMY_BINDS'] = {
    'db1': app.config['SQLALCHEMY_DATABASE_URI'],
}

root_path = os.path.abspath("%s/.." % os.path.dirname(__file__))
tmp_path = "%s/tmp" % root_path

os.environ['BOTO_ENDPOINTS'] = os.path.abspath(
    "%s/config/boto_endpoints.json" % root_path)

###################
# ASSETS SETTINGS #
###################
assets = Environment(app)
loader = YAMLLoader("%s/assets/assets.yml" % root_path)
bundles = loader.load_bundles()
assets.register(bundles)

assets.set_directory("%s/public" % root_path)
assets.load_path.append('./assets/')
assets.url = '/'
assets.manifest = "json:%s/public/gen/webassets-manifest.json" % root_path

development_mode = not environment.equals('production')
assets.cache = development_mode
assets.auto_build = development_mode
assets.debug = development_mode

# MD Feb-2015 Allow created files to be group writeable. This will fix some problems with files created in the /tmp
# directory that are accessed both by Celery and duesty scripts. The /tmp directory should have set "chmod g+s tmp"
Example #46
0
 def from_yaml(self, path):
     """Register bundles from a YAML configuration file"""
     bundles = YAMLLoader(path).load_bundles()
     for name in bundles:
         self.register(name, bundles[name])
Example #47
0
__author__ = 'hsk81'

###############################################################################
###############################################################################

from flask.ext.assets import Environment
from webassets.loaders import YAMLLoader

from ..app import app

###############################################################################
###############################################################################

loader = YAMLLoader(app.config['YML_FILE'])
bundles = loader.load_bundles()

assets = Environment(app)
assets.manifest = 'cache'
assets.register(bundles)
assets.url = app.config.get('CDN')

###############################################################################
###############################################################################
Example #48
0
 def loader(self, text, filename=None):
     io = StringIO(textwrap.dedent(text))
     if filename:
         io.name = filename
     return YAMLLoader(io)
Example #49
0
# Copyright (c) 2018 Tildes contributors <*****@*****.**>
# SPDX-License-Identifier: AGPL-3.0-or-later

from webassets.loaders import YAMLLoader

WEBASSETS_ENV = YAMLLoader("webassets.yaml").load_environment()


def test_scripts_file_first_in_bundle():
    """Ensure that the main scripts.js file will be at the top."""
    js_bundle = WEBASSETS_ENV["javascript"]

    first_filename = js_bundle.resolve_contents()[0][0]

    assert first_filename == "js/scripts.js"


def test_styles_file_last_in_bundle():
    """Ensure that the main styles.css file will be at the bottom."""
    css_bundle = WEBASSETS_ENV["css"]

    last_filename = css_bundle.resolve_contents()[-1][0]

    assert last_filename == "css/styles.css"