Ejemplo n.º 1
0
def create_app(object_name='bosphorus.settings', env='dev'):
    
    app = create_barebones_app(object_name, env)

    # Import and register the different asset bundles
    assets_env = Environment()
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().iteritems():
        assets_env.register(name, bundle)

    # register our blueprints
    from controllers.main import main
    from controllers.user import user
    from controllers.studies import studies
    from controllers.person import person
    from controllers.protocol import protocol
    from utils import proxy
    app.register_blueprint(main)
    app.register_blueprint(user)
    app.register_blueprint(person)
    app.register_blueprint(studies)
    app.register_blueprint(protocol)
    app.register_blueprint(proxy)

    return app
Ejemplo n.º 2
0
def init_app(app):
    assets = Environment(app)
    assets.register("css_vendor", css_vendor)
    assets.register("js_vendor", js_vendor)
    assets.register("css_linkedlist", css_linkedlist)
    assets.manifest = 'cache' if not app.debug else False
    assets.cache = not app.debug
    assets.debug = app.debug
Ejemplo n.º 3
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('css_all', css_all)
    webassets.register('js_vendor', js_vendor)
    webassets.register('js_main', js_main)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Ejemplo n.º 4
0
class InvenioAssets(object):
    """Invenio asset extension."""

    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.env = Environment()
        self.collect = Collect()

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, entry_point_group='invenio_assets.bundles',
                 **kwargs):
        """Initialize application object.

        :param app: An instance of :class:`~flask.Flask`.
        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        self.init_config(app)
        self.env.init_app(app)
        self.collect.init_app(app)

        if entry_point_group:
            self.load_entrypoint(entry_point_group)
        app.extensions['invenio-assets'] = self

    def init_config(self, app):
        """Initialize configuration.

        :param app: An instance of :class:`~flask.Flask`.
        """
        app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')
        app.config.setdefault(
            'COLLECT_FILTER', partial(collect_staticroot_removal, app))

    def load_entrypoint(self, entry_point_group):
        """Load entrypoint.

        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        for ep in pkg_resources.iter_entry_points(entry_point_group):
            self.env.register(ep.name, ep.load())
Ejemplo n.º 5
0
 def init_app(self, app):
     env = Environment(app)
     env.url_expire = True
     env.register('css_app', css_app)
     env.register('js_app', js_app)
     env.manifest = 'cache' if not app.debug else False
     env.cache = not app.debug
     env.debug = app.debug
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
def init_app(app):
    webassets = Environment(app)
    webassets.url = app.static_url_path
    webassets.register('js_lodjers', js_lodjers)
    webassets.register('js_mixpanel', js_mixpanel)
    webassets.register('css_lodjers', css_lodjers)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Ejemplo n.º 8
0
def init_app(app, allow_auto_build=True):
    assets = Environment(app)
    # on google app engine put manifest file beside code
    # static folders are stored separately and there is no access to them in production
    folder = os.path.abspath(os.path.dirname(__file__)) if "APPENGINE_RUNTIME" in os.environ else ""
    assets.directory = os.path.join(app.static_folder, "compressed")
    assets.manifest = "json:{}/manifest.json".format(assets.directory)
    assets.url = app.static_url_path + "/compressed"
    compress = not app.debug  # and False
    assets.debug = not compress
    assets.auto_build = compress and allow_auto_build
    assets.register('js', Bundle(*JS, filters='yui_js', output='script.%(version)s.js'))
    assets.register('css', Bundle(*CSS, filters='yui_css', output='style.%(version)s.css'))
Ejemplo n.º 9
0
def register_assets(app):
    """Register Webassets in the app"""
    _create_code_css(app)

    assets = Environment(app)
    bundle = Bundle('style/main.less', 'style/code.css',
                    filters='less,cleancss',
                    output='css/main.%(version)s.css')
    assets.register('css', bundle)
    app.add_url_rule(
        '/static/fonts/bootstrap/<path:filename>',
        'bootstrap_fonts',
        bootstrap_fonts)
Ejemplo n.º 10
0
def register_assets(app):
    bundles = {
        'home_js': Bundle('style/js/jquery.min.js',
                          'style/js/bootstrap.min.js',
                          'style/honmaple.js',
                          output='style/assets/home.js',
                          filters='jsmin'),
        'home_css': Bundle('style/css/bootstrap.min.css',
                           'style/honmaple.css',
                           output='style/assets/home.css',
                           filters='cssmin')
    }

    assets = Environment(app)
    assets.register(bundles)
Ejemplo n.º 11
0
class TestConfigNoAppBound:
    """The application is not bound to a specific app.
    """

    def setup(self):
        self.env = Environment()

    def test_no_app_available(self):
        """Without an application bound, we can't do much."""
        assert_raises(RuntimeError, setattr, self.env, 'debug', True)
        assert_raises(RuntimeError, self.env.config.get, 'debug')

    def test_global_defaults(self):
        """We may set defaults even without an application, however."""
        self.env.config.setdefault('FOO', 'BAR')
        with Flask(__name__).test_request_context():
            assert self.env.config['FOO'] == 'BAR'

    def test_multiple_separate_apps(self):
        """Each app has it's own separate configuration.
        """
        app1 = Flask(__name__)
        self.env.init_app(app1)

        # With no app yet available...
        assert_raises(RuntimeError, getattr, self.env, 'url')
        # ...set a default
        self.env.config.setdefault('FOO', 'BAR')

        # When an app is available, the default is used
        with app1.test_request_context():
            assert self.env.config['FOO'] == 'BAR'

            # If the default is overridden for this application, it
            # is still valid for other apps.
            self.env.config['FOO'] = '42'
            assert self.env.config['FOO'] == '42'
            app2 = Flask(__name__)
            with app2.test_request_context():
                assert self.env.config['FOO'] == 'BAR'

    def test_key_error(self):
        """KeyError is raised if a config value doesn't exist.
        """
        with Flask(__name__).test_request_context():
            assert_raises(KeyError, self.env.config.__getitem__, 'YADDAYADDA')
            # The get() helper, on the other hand, simply returns None
            assert self.env.config.get('YADDAYADDA') == None
Ejemplo n.º 12
0
def register_assets(app):
    assets = Environment(app)
    assets.debug = app.debug
    assets.auto_build = True
    assets.url = app.static_url_path

    css_blog = Bundle(*BLOG_ASSETS, filters='cssmin', output='css/blog.min.css')
    css_welcome = Bundle(*INDEX_ASSETS, filters='cssmin', output='css/welcome.min.css')

    js_all = Bundle(*JS_ASSETS, filters='rjsmin', output='js/all.min.js')

    assets.register('css_blog', css_blog)
    assets.register('css_welcome', css_welcome)
    assets.register('js_all', js_all)
    app.logger.info("Registered assets...")

    return assets
Ejemplo n.º 13
0
    def __init__(self, app=None, entrypoint="invenio_assets.bundles", **kwargs):
        """Extension initialization."""
        self.env = Environment()
        self.collect = Collect()
        self.entrypoint = entrypoint

        if app:
            self.init_app(app, **kwargs)
Ejemplo n.º 14
0
def register_assets(app):
    bundles = {

        'home_js': Bundle(
            'style/js/jquery.min.js',      #这里直接写static目录的子目录 ,如static/bootstrap是错误的
            'style/js/bootstrap.min.js',
            output='style/assets/home.js',
            filters='jsmin'),

        'home_css': Bundle(
            'style/css/bootstrap.min.css',
            output='style/assets/home.css',
            filters='cssmin')
        }

    assets = Environment(app)
    assets.register(bundles)
Ejemplo n.º 15
0
def register_assets(app):
	assets = Environment(app)
	assets.url = app.static_url_path
	assets.directory = app.static_folder
	assets.append_path('assets')
	scss = Bundle('scss/main.scss', filters='pyscss', output='main.css', depends=('scss/*.scss'))
	assets.register('scss_all', scss)
Ejemplo n.º 16
0
def create_app():
    template_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
    static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')

    css_bundle = Bundle(
        'build/css/*.css',
        output='public/main.css')

    js_bundle = Bundle(
        'build/js/*.js',
        output='public/main.js')

    fonts_bundle = Bundle(
        'fonts/bootstrap/*')

    app = appfactory.create_app(
        'frontend',
        blueprints=blueprints,
        static_folder=static_folder,
        template_folder=template_folder)

    env = Environment(app)
    env.register('css_main', css_bundle)
    env.register('js_main', js_bundle)
    env.register('fonts_bundle', fonts_bundle)

    return app
Ejemplo n.º 17
0
def prepare(app):
    web_assets = Environment(app)

    web_assets.register('css_all', *prepare_css())
    web_assets.register('js_all', *prepare_js())

    is_debugging = app.debug
    web_assets.manifest = 'cache' if not is_debugging else False
    web_assets.cache = not is_debugging
    web_assets.debug = is_debugging

    return app
Ejemplo n.º 18
0
def create_app(object_name='bosphorus.settings', env='dev'):

    app = Flask(__name__)

    # set config
    app.config.from_object(object_name)
    app.config['ENV'] = env
    app.config['DEBUG'] = False if env=="prod" else True

    # register all custom jinja filters
    for f in jinja_filters:
        app.jinja_env.filters[f[0]] = f[1]

    #init the cache
    cache.init_app(app)

    #init SQLAlchemy
    db.init_app(app)

    #init Orthanc
    orthanc.init_app(app)

    # Import and register the different asset bundles
    assets_env = Environment()
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().iteritems():
        assets_env.register(name, bundle)

    # register our blueprints
    from controllers.main import main
    from controllers.user import user
    from controllers.studies import studies
    from controllers.person import person
    from utils import proxy
    app.register_blueprint(main)
    app.register_blueprint(user)
    app.register_blueprint(person)
    app.register_blueprint(studies)
    app.register_blueprint(proxy)

    return app
Ejemplo n.º 19
0
    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.env = Environment()
        self.collect = Collect()

        if app:
            self.init_app(app, **kwargs)
Ejemplo n.º 20
0
def register_assets():
    from flask_assets import Bundle, Environment

    css_vendor = Bundle("assets/css/bootstrap.min.css",
                        "assets/css/font-awesome.css",
                        "assets/css/messenger.css",
                        "assets/css/messenger-theme-flat.css",
                        "assets/css/share.min.css",
                        filters="cssmin",
                        output="assets/css/vendor.css")

    js_vendor = Bundle("assets/js/jquery.min.js",
                       "assets/js/bootstrap.min.js",
                       "assets/js/messenger.min.js",
                       "assets/js/messenger-theme-flat.js",
                       output="assets/js/vendor.js")

    wechat_css = Bundle("assets/css/weui.min.css",
                        "assets/css/weui2.min.css",
                        "assets/css/font-awesome.css",
                        "assets/css/messenger.css",
                        "assets/css/messenger-theme-flat.css",
                        "assets/css/share.min.css",
                        filters="cssmin",
                        output="assets/css/wechat.css")

    wechat_js = Bundle("assets/js/zepto.min.js",
                       "assets/js/jquery.min.js",
                       "assets/js/bootstrap.min.js",
                       "assets/js/messenger.min.js",
                       "assets/js/messenger-theme-flat.js",
                       "assets/js/wechat/login/login.js",
                       output="assets/js/wechat.js")

    assets = Environment()
    assets.register('css_vendor', css_vendor)
    assets.register('wechat_css', wechat_css)
    assets.register('js_vendor', js_vendor)
    assets.register('wechat_js', wechat_js)

    return assets
Ejemplo n.º 21
0
    def register_extensions(self, app):
        if app.debug:
            debug_toolbar = DebugToolbarExtension()
            debug_toolbar.init_app(app)

        db.init_app(app)
        mail.init_app(app)
        wtf.add_helpers(app)

        s3.init_app(app)

        assets = Environment(app)
        assets.register(bundles)

        admin.init_app(app)

        register_health_check(app, db)

        # Setup Flask-Security
        user_datastore = SQLAlchemyUserDatastore(db, User, Role)
        app.security = Security(app, user_datastore)
Ejemplo n.º 22
0
class TestUrlAndDirectoryWithInitApp(object):
    """[Regression] Make sure the automatic "directory" and "url"
    values also work if the application is initialized via "init_app()".
    """

    def setup(self):
        self.app = Flask(__name__, static_path='/initapp_static')
        self.env = Environment()
        self.env.init_app(self.app)

    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', env=self.env).urls() == ['/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']
Ejemplo n.º 23
0
def init():
    """
    Sets up flask application object `app` and returns it.
    """
    # Instantiate main app, load configs, register modules, set
    # url patterns and return the `app` object.
    app = Flask(__name__)
    app.config.from_object(settings)
    config.app = app
    # Init SQLAlchemy wrapper.
    config.db = SQLAlchemy(app)
    if app.debug:
        DebugToolbarExtension(app)
    #: Wrap the `app` with `Babel` for i18n.
    Babel(app)

    config.cache = Cache(app)
    config.bcrypt = Bcrypt(app)
    # Other initializations.
    for fn, values in [(set_middlewares, getattr(settings, 'MIDDLEWARES', None)),
                       (set_context_processors, getattr(settings, 'CONTEXT_PROCESSORS', None)),
                       (set_template_filters, getattr(settings, 'TEMPLATE_FILTERS', None)),
                       (set_before_handlers, getattr(settings, 'BEFORE_REQUESTS', None)),
                       (set_after_handlers, getattr(settings, 'AFTER_REQUESTS', None)),
                       (set_log_handlers, getattr(settings, 'LOG_HANDLERS', None)),
                       (set_error_handlers, getattr(settings, 'ERROR_HANDLERS', None)),
                       (set_blueprints, getattr(settings, 'BLUEPRINTS', None))]:
        if values:
            fn(app, values)

    # Register all js and css files.
    assets = Environment(app)
    for name, bundle in webassets.loaders.YAMLLoader('assets.yml').load_bundles().items():
        assets.register(name, bundle)

    # URL rules.
    urls.set_urls(app)
    # Set flask-cli commands
    import commands
    return app
Ejemplo n.º 24
0
    def install(cls, app):
        """Install the extension into the application."""
        Environment.resolver_class = InvenioResolver
        env = Environment(app)
        env.url = "{0}/{1}/".format(app.static_url_path,
                                    app.config["ASSETS_BUNDLES_DIR"])
        env.directory = os.path.join(app.static_folder,
                                     app.config["ASSETS_BUNDLES_DIR"])
        env.append_path(app.static_folder)
        env.auto_build = app.config.get("ASSETS_AUTO_BUILD", True)

        # The filters less and requirejs don't have the same behaviour by
        # default. Make sure we are respecting that.
        app.config.setdefault("LESS_RUN_IN_DEBUG", True)
        app.config.setdefault("REQUIREJS_RUN_IN_DEBUG", False)
        # Fixing some paths as we forced the output directory with the
        # .directory
        app.config.setdefault("REQUIREJS_BASEURL", app.static_folder)
        requirejs_config = os.path.join(env.directory,
                                        app.config["REQUIREJS_CONFIG"])
        if not os.path.exists(requirejs_config):
            app.config["REQUIREJS_CONFIG"] = os.path.relpath(
                os.path.join(app.static_folder,
                             app.config["REQUIREJS_CONFIG"]),
                env.directory)

        app.jinja_env.add_extension(BundleExtension)
        app.context_processor(BundleExtension.inject)
Ejemplo n.º 25
0
def init_app(app):
    """
    Initilize assets.
    :param app:
    """
    webassets = Environment(app)
    webassets.url = app.static_url_path
    webassets.register('css_all', css_all)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Ejemplo n.º 26
0
def welcome(app):
    assets = Environment(app)

    js = Bundle(
        'js/modernizr.js',
        'js/jquery.js',
        'js/foundation.min.js',
        'js/main.js',
        filters='rjsmin',
        output='js/min.js'
    )
    assets.register('js', js)

    css = Bundle(
        'css/foundation.css',
        'css/main.css',
        filters='cssmin',
        output='css/min.css'
    )
    assets.register('css', css)

    return render_template('index.html')
Ejemplo n.º 27
0
class InvenioAssets(object):
    """Invenio asset extension."""

    def __init__(self, app=None, entrypoint='invenio_assets.bundles',
                 **kwargs):
        """Extension initialization."""
        self.env = Environment()
        self.collect = Collect()
        self.entrypoint = entrypoint

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, **kwargs):
        """Initialize application object."""
        self.init_config(app)
        self.env.init_app(app)
        self.collect.init_app(app)
        self.init_cli(app.cli)
        if self.entrypoint:
            self.load_entrypoint(self.entrypoint)
        app.extensions['invenio-assets'] = self

    def init_config(self, app):
        """Initialize configuration."""
        app.config.setdefault("REQUIREJS_BASEURL", app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')

    def init_cli(self, cli):
        """Initialize CLI."""
        cli.add_command(assets_cmd)
        cli.add_command(npm)
        cli.add_command(collect)

    def load_entrypoint(self, entrypoint):
        """Load entrypoint."""
        for ep in pkg_resources.iter_entry_points(entrypoint):
            self.env.register(ep.name, ep.load())
Ejemplo n.º 28
0
def init(app) -> None:
    """
    Bundle projects assets.

    :param app: Main application instance
    :type app: flask.Flask
    """
    assets = Environment(app)
    assets.auto_build = app.config.get('ASSETS_AUTO_BUILD', True)
    files_to_watch = []

    if 'COLLECT_STATIC_ROOT' in app.config:
        assets.cache = app.config['COLLECT_STATIC_ROOT']
        collect = Collect()
        collect.init_app(app)
        collect.collect()
        app.static_folder = app.config['COLLECT_STATIC_ROOT']

    for key in ['js', 'css']:
        assets_key = '%s_ASSETS' % key.upper()
        build_files = app.config[assets_key]

        files_to_watch.extend(_get_files_for_settings(app, assets_key))

        bundle = Bundle(*build_files,
                        output=app.config['%s_OUTPUT' % assets_key],
                        filters=app.config['%s_FILTERS' % assets_key]
                        )

        assets.register('%s_all' % key, bundle)

        app.logger.debug('Bundling files: %s%s',
                         os.linesep,
                         os.linesep.join(build_files))

    app.assets = assets
    app._base_files_to_watch = files_to_watch

    app.logger.info('Base assets are collected successfully.')
Ejemplo n.º 29
0
def create_assets(app):
    js_filters = ['jsmin'] if not app.debug else []
    js = Bundle(
        'javascripts/app.js',
        'javascripts/libs/jquery/jquery-1.11.2.js',
        'javascripts/libs/jqcloud/jqcloud-1.0.4.js',
        filters=js_filters,
        output='js/app.js')

    css_filters = ['cssmin', 'stylus'] if not app.debug else []
    css = Bundle(
        'stylesheets/style.css',
        'stylesheets/jqcloud.css',
        'stylesheets/code.css',
        filters=css_filters,
        output='css/style.css')

    # names the assets to be used in templates
    assets = Environment(app)
    assets.register('js_all', js)
    assets.register('css_all', css)
    return assets
Ejemplo n.º 30
0
def init_app(app):
    webassets = Environment(app)

    webassets.register('css_bootstrap', css_bootstrap)
    #webassets.register('css_local', css_local)

    #webassets.register('js_local', js_local)
    #webassets.register('js_jquery', js_jquery)
    webassets.register('js_bootstrap', js_bootstrap)
    #webassets.register('js_angular', js_angular)
    #webassets.register('js_coffee', js_coffee)

    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Ejemplo n.º 31
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
    app.config['VERSION_PATH'] = version_path
    log_config_change('VERSION_PATH', version_path)

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

    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)
    app.config['BUGZILLA_URL'] = _lookup_service_url(lando_api_url, 'bugzilla')
    log_config_change('BUGZILLA_URL', app.config['BUGZILLA_URL'])
    app.config['PHABRICATOR_URL'] = (_lookup_service_url(
        lando_api_url, 'phabricator'))
    log_config_change('PHABRICATOR_URL', app.config['PHABRICATOR_URL'])

    # Set remaining configuration
    app.config['SECRET_KEY'] = secret_key
    app.config['SESSION_COOKIE_NAME'] = session_cookie_name
    log_config_change('SESSION_COOKIE_NAME', session_cookie_name)
    app.config['SESSION_COOKIE_DOMAIN'] = session_cookie_domain
    log_config_change('SESSION_COOKIE_DOMAIN', session_cookie_domain)
    app.config['SESSION_COOKIE_SECURE'] = session_cookie_secure
    log_config_change('SESSION_COOKIE_SECURE', session_cookie_secure)
    app.config['SERVER_NAME'] = session_cookie_domain
    log_config_change('SERVER_NAME', session_cookie_domain)
    app.config['USE_HTTPS'] = use_https
    log_config_change('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
Ejemplo n.º 32
0
    return gavel


app = start_app()

app.config['DEBUG'] = os.environ.get('DEBUG', False)

import gavel.settings as settings

app.config['SQLALCHEMY_DATABASE_URI'] = settings.DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = settings.SECRET_KEY

from flask_assets import Environment, Bundle

assets = Environment(app)
assets.config['pyscss_style'] = 'expanded'
assets.url = app.static_url_path

bundles = {
    'scss_all':
    Bundle('css/style.scss',
           depends='**/*.scss',
           filters=(
               'pyscss',
               'cssmin',
           ),
           output='all.css'),
    'admin_js':
    Bundle('js/admin/jquery.tablesorter.min.js',
           'js/admin/jquery.tablesorter.widgets.js',
Ejemplo n.º 33
0
Archivo: core.py Proyecto: tomjie/aleph
from flask_mail import Mail
from kombu import Exchange, Queue
from celery import Celery
from py2neo import Graph
from elasticsearch import Elasticsearch

from aleph import default_settings, archive
from aleph.ext import get_init

log = logging.getLogger(__name__)

db = SQLAlchemy()
migrate = Migrate()
mail = Mail()
celery = Celery('aleph')
assets = Environment()
oauth = OAuth()
oauth_provider = oauth.remote_app('provider', app_key='OAUTH')


def create_app(config={}):
    app = Flask('aleph')
    app.config.from_object(default_settings)
    if config.get('TESTING'):
        app.config.from_envvar('ALEPH_TEST_SETTINGS', silent=True)
    else:
        app.config.from_envvar('ALEPH_SETTINGS', silent=True)
    app.config.update(config)
    app_name = app.config.get('APP_NAME')

    if not app.debug and app.config.get('MAIL_ADMINS'):
Ejemplo n.º 34
0
from module import tools, user_auth, produce
from flask_debugtoolbar import DebugToolbarExtension
import conf


class MyFlask(Flask):
    jinja_environment = conf.FlaskEchartsEnvironment


app = MyFlask(__name__)
DB = SQLAlchemy(app)
mail = Mail(app)
limiter = conf.WebLimiter()
limiter = limiter.limiter
moment = Moment(app)
assets = Environment(app)
app.config.from_pyfile('conf/main.conf')
app.config.from_pyfile('conf/sql.conf')
app.config.from_pyfile('conf/redis.conf')
app.config.get('TRAP_HTTP_EXCEPTIONS')
app.secret_key = app.config.get('SECRET_KEY')
app.debug = False
task_run = produce.SchedulerBackgroud()
toolbar = DebugToolbarExtension(app)
ssl._create_default_https_context = ssl._create_unverified_context
app.register_blueprint(Assets.page_Assets)
app.register_blueprint(assets_manage.page_assets_manage)
app.register_blueprint(publish.page_publish)
app.register_blueprint(resource_pool.page_resource_pool)
app.register_blueprint(chart_center.page_chart_center)
app.register_blueprint(examine.page_examine)
Ejemplo n.º 35
0
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or 'DEBUGSECRETKEY'
app.config['APP_URL'] = os.environ.get('APP_URL')
app.config['MAILGUN_DOMAIN'] = os.environ.get('MAILGUN_DOMAIN')
app.config['MAILGUN_KEY'] = os.environ.get('MAILGUN_KEY')
app.config['FLASKS3_CDN_DOMAIN'] = os.environ.get('FLASKS3_CDN_DOMAIN')
app.config['FLASKS3_BUCKET_NAME'] = os.environ.get('FLASKS3_BUCKET_NAME')
app.config['FLASKS3_HEADERS'] = {'Cache-Control': 'max-age=31536000'}
app.config['FLASKS3_GZIP'] = True
app.config['FLASK_ASSETS_USE_S3'] = True

if os.environ.get('FLASK_DEBUG'):
    app.config['ASSETS_DEBUG'] = True
    app.config['FLASK_ASSETS_USE_S3'] = False

s3 = FlaskS3(app)
assets = Environment(app)
assets.register(
    'css_all',
    Bundle('main.css', output='main.%(version)s.css'),
)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'


@login_manager.user_loader
def load_user(user_id):
    try:
        user = User.get(User.id == user_id)
    except User.DoesNotExist:
Ejemplo n.º 36
0
def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')

    app.config.from_object(Config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    Config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    return app
Ejemplo n.º 37
0
model2 = load_model('model/test3.h5')
loss = {'ctc': lambda y_true, y_pred: y_pred}
optimizer = SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)

model2.compile(loss=loss, optimizer=optimizer)

app = Flask(__name__)
UPLOAD_FOLDER = './UPLOADED_AUDIO'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['TEMPLATES_AUTO_RELOAD'] = True

js = Bundle('microphoneController.js',
            'jquery-3.5.1.min.js',
            'recorder.js',
            output='gen/main.js')
assets = Environment(app)
assets.register('main_js', js)


@app.route('/')
def index():
    return render_template('index.html')


# https://blog.addpipe.com/using-recorder-js-to-capture-wav-audio-in-your-html5-web-site/
@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == "POST":
        file = request.files['file']
        filename = secure_filename(file.filename)
Ejemplo n.º 38
0
login_manager.init_app(application)

js = Bundle('js/helper.js',
            'js/add-products.js',
            'js/lettering.js',
            'js/front-page.js',
            'js/search.js',
            'js/ajax.js',
            'js/setup.js',
            output='gen/main.js')
css = Bundle('css/style.css',
             'css/lettering.css',
             'css/vendor/pagination.css',
             output='gen/style.css')

assets = Environment(application)

assets.debug = CONFIG.ASSET_DEBUG

assets.register('main_js', js)
assets.register('main_css', css)


class User(UserMixin):
    pass


@login_manager.user_loader
def user_loader(username):
    if username not in CONFIG.USERS:
        return
Ejemplo n.º 39
0
# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment

css = Bundle('libs/bootswatch-dist/css/bootstrap.css',
             'css/style.css',
             filters='cssmin',
             output='public/css/common.css')

js = Bundle('libs/jQuery/dist/jquery.js',
            'libs/bootswatch-dist/js/bootstrap.js',
            'js/plugins.js',
            filters='jsmin',
            output='public/js/common.js')

assets = Environment()

assets.register('js_all', js)
assets.register('css_all', css)
Ejemplo n.º 40
0
    except Exception:
        raise ImportError(f"Please make sure that the extension `{ext.code}` follows conventions.")


# filters
# -------

app.jinja_env.globals["DEBUG"] = app.config["DEBUG"]
app.jinja_env.globals["EXTENSIONS"] = valid_extensions
app.jinja_env.globals["SITE_TITLE"] = getenv("LNBITS_SITE_TITLE", "LNbits")


# assets
# ------

assets = Environment(app)
assets.url = app.static_url_path
assets.register("base_css", Bundle("scss/base.scss", filters="pyscss", output="css/base.css"))


# commands
# --------

@app.cli.command("migrate")
def migrate_databases():
    """Creates the necessary databases if they don't exist already; or migrates them."""
    core_migrations.migrate()

    for ext in valid_extensions:
        try:
            ext_migrations = importlib.import_module(f"lnbits.extensions.{ext.code}.migrations")
Ejemplo n.º 41
0
def setupAssets(app):
    createStorage()
    assets = Environment(app)
    assets.init_app(app)
    assets.register("js_all", bundleJavascripts())
    assets.register("css_all", bundleStylesheets())
Ejemplo n.º 42
0

import os
import sqlite3
import sys

#create application
app = Flask(__name__)
app.config['SECRET_KEY']= 'GRADSCHOOLNOLIFE'
app.config.from_object(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:////Users/zengyh/myproject/21days/buddyprogram.db'
#app.config['SQLALCHEMY_DATABASE_URI']='sqlite:////Users/Yu/Desktop/buddy/buddyprogram.db'
#app.config['SQLALCHEMY_DATABASE_URI']='sqlite:////Users/bichengxu/Desktop/si699_03_developing_social_computing/21days/buddyprogram.db'

cs = Bundle('devices.min.css','bootstrap.min.css', output='gen/main.css')
assets = Environment(app)
assets.register('main_css',cs)

db = SQLAlchemy(app)
login_manager = LoginManager() #handle user session
login_manager.init_app(app)
login_manager.login_view = 'login'

# config for updating intermediate table participate
###########################
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'buddyprogram.db'),
))
app.config.from_envvar('BUDDY_SETTINGS', silent=True)
def connect_db():
    rv = sqlite3.connect(app.config['DATABASE'])
Ejemplo n.º 43
0
class InvenioAssets(object):
    """Invenio asset extension."""

    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.env = Environment()
        self.collect = Collect()
        self.webpack = FlaskWebpackExt()

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, entry_point_group='invenio_assets.bundles',
                 **kwargs):
        """Initialize application object.

        :param app: An instance of :class:`~flask.Flask`.
        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        self.init_config(app)
        self.env.init_app(app)
        self.collect.init_app(app)
        self.webpack.init_app(app)

        if entry_point_group:
            self.load_entrypoint(entry_point_group)

        app.extensions['invenio-assets'] = self

    def init_config(self, app):
        """Initialize configuration.

        :param app: An instance of :class:`~flask.Flask`.
        """
        app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')
        app.config.setdefault(
            'COLLECT_FILTER', partial(collect_staticroot_removal, app))
        app.config.setdefault(
            'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')

    def load_entrypoint(self, entry_point_group):
        """Load entrypoint.

        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        for ep in pkg_resources.iter_entry_points(entry_point_group):
            self.env.register(ep.name, ep.load())
Ejemplo n.º 44
0
from flask import Flask, render_template, redirect, request, url_for, jsonify, session
from flask_assets import Bundle, Environment
import os
import sys
import subprocess
import json

app = Flask(__name__)
app.secret_key = "super secret key"

env = Environment(app)
js = Bundle('js/clarity-icons.min.js', 'js/clarity-icons-api.js',
            'js/clarity-icons-element.js', 'js/custom-elements.min.js')
env.register('js_all', js)
css = Bundle('css/override.css','css/clarity-ui-dark.min.css', 'css/clarity-icons.min.css')
env.register('css_all', css)

@app.route('/')
def homepage():
    return render_template('index.html')

@app.route('/health')
def health():
    return jsonify(test="success")

if __name__ == '__main__':
    app.run(debug=True)
Ejemplo n.º 45
0
import os
import chess
from flask import Flask, render_template, request, jsonify, send_from_directory, redirect
from flask_socketio import SocketIO
from flask_assets import Environment, Bundle
from database import *

app = Flask(__name__)
socketio = SocketIO(app)
assets = Environment()
assets.init_app(app)


def get_str(board):
    return str(board).replace(' ', '').replace('\n', '')


@app.route('/')
def hello():
    return redirect("/games", code=302)


@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static/gen/img'),
                               'favicon.ico',
                               mimetype='image/vnd.microsoft.icon')


@app.route('/new_game')
def new_game():
Ejemplo n.º 46
0
from app import app
from flask import render_template, redirect, url_for
from instagram_web.blueprints.users.views import users_blueprint
from instagram_web.blueprints.sessions.views import sessions_blueprint
from instagram_web.blueprints.imgs.views import imgs_blueprint
from instagram_web.blueprints.donations.views import donations_blueprint
from instagram_web.blueprints.follows.views import follows_blueprint
from flask_assets import Environment, Bundle
from .util.assets import bundles
from flask_login import LoginManager, current_user, login_required
from models.user import User
from instagram_web.util.google_oauth import oauth

assets = Environment(app)
assets.register(bundles)

app.register_blueprint(users_blueprint, url_prefix="/users")
app.register_blueprint(sessions_blueprint, url_prefix="/sessions")
app.register_blueprint(imgs_blueprint, url_prefix="/imgs")
app.register_blueprint(donations_blueprint, url_prefix="/donations")
app.register_blueprint(follows_blueprint, url_prefix="/follows")
login_manager = LoginManager()
login_manager.init_app(app)

oauth.init_app(app)
# login_manager.login_view = "sessions."


@login_manager.user_loader
def load_user(user_id):
    return User.get_by_id(user_id)
Ejemplo n.º 47
0
from celery import Celery
from flask import Flask
from flask_assets import Environment as FlaskAssets, Bundle
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

app.config.from_object('config.Config')
app.secret_key = app.config['SECRET_KEY']

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

assets = FlaskAssets(app)
assets.register('js_base', Bundle(
    join('js', 'jquery-1.12.4.js'),
    join('js', 'bootstrap-3.3.7.js'),
    filters='jsmin',
    output=join('gen', 'js.%(version)s.min.js'))
)
assets.register('js_activity', Bundle(
    join('js', 'activity.js'),
    filters='jsmin',
    output=join('gen', 'activity.%(version)s.min.js'))
)
assets.register('css_base', Bundle(
    join('css', 'bootstrap.css'),
    join('css', 'font-awesome.css'),
    join('css', 'app.css'),
Ejemplo n.º 48
0
import os

from flask import Flask, send_from_directory
from flask import request, jsonify, render_template
from flask_socketio import SocketIO
from flask_assets import Environment
from flask_autoindex import AutoIndex

from fgclassifier.visualizer import actions
from fgclassifier.visualizer.options import dataset_choices, fm_choices
from fgclassifier.visualizer.options import clf_choices

from fgclassifier.utils import get_stats

app = Flask(__name__)
assets = Environment(app)
app.config['SECRECT_KEY'] = os.getenv('FLASK_SECRECT_KEY', 'keyboardcat!')
app.config['ASSETS_DEBUG'] = os.getenv('FLASK_ENV') == 'development'
socketio = SocketIO(app)


@app.route('/')
def index():
    """The Index Page"""
    inputs = actions.parse_inputs(**dict(request.args.items()))
    tmpl_data = {
        'dataset_choices': dataset_choices,
        'fm_choices': fm_choices,
        'clf_choices': clf_choices,
        **inputs,
        **actions.predict_one(**inputs)
Ejemplo n.º 49
0
    def __call__(cls, flask_or_import_name, project=None, directory=None,
                 config=None, exceptions=None, compress_html=True,
                 skip_views=False):
        """
        Allow to register all subclasses of Juice at once

        If a class doesn't have a route base, it will create a dasherize version
        of the class name.

        So we call it once initiating
        :param flask_or_import_name: Flask instance or import name -> __name__
        :param project: name of the project. If the directory and config is empty, it will guess them from here
        :param directory: The directory containing your project's Views, Templates and Static
        :param config: string of config object. ie: "app.config.Dev"
        :param exceptions: The exceptions path to load
        :param compress_html: bool - If true it will use the plugin "htmlcompress"
                to remove white spaces off the html result
        :param skip_views: bool - If true, it will setup everything but registering the views
        """

        if isinstance(flask_or_import_name, Flask):
            app = flask_or_import_name
        else:
            app = Flask(flask_or_import_name)

        app.wsgi_app = ProxyFix(app.wsgi_app)

        app.url_map.converters['regex'] = RegexConverter

        if not directory:
            directory = "application/%s" % project if project else "."

        if not config:
            config = "application.config.%s" % get_env()

        app.config.from_object(config)

        # Extensions to remove extra white spaces in html
        if compress_html:
            app.jinja_env.add_extension('juice.extras.htmlcompress.HTMLCompress')

        if directory:
            app.template_folder = directory + "/templates"
            app.static_folder = directory + "/static"

        if exceptions:
            abort.map_from_module(exceptions)

        cls._app = app

        cls._setup_logger()

        cls._add_asset_bundle(app.static_folder)

        # Flask Assets
        cls.assets = Environment(cls._app)

        # Register templates
        if cls._template_paths:
            loader = [cls._app.jinja_loader] + list(cls._template_paths)
            cls._app.jinja_loader = jinja2.ChoiceLoader(loader)

        # Register static
        if cls._static_paths:
            loader = [cls._app.static_folder] + list(cls._static_paths)
            cls.assets.load_path = loader

        # init_app
        [_app(cls._app) for _app in cls._init_apps]

        # Register all views
        if not skip_views:
            for subcls in cls.__subclasses__():
                base_route = subcls.base_route
                if not base_route:
                    base_route = utils.dasherize(utils.underscore(subcls.__name__))
                    if subcls.__name__.lower() == "index":
                        base_route = "/"
                subcls.register(cls._app, base_route=base_route)

        # Load all bundles
        [cls.assets.from_yaml(a) for a in cls._asset_bundles]

        @cls._app.after_request
        def _after_request_cleanup(response):
            cls._global["__META__"] = cls._default_page_meta
            return response

        return cls._app
Ejemplo n.º 50
0
#-*- coding=utf8 -*-
'''
write by xii
'''
from flask import Flask
from flask_assets import Environment, Bundle
from config import Config

app = Flask(__name__, template_folder='./template')

app.config['SECRET_KEY'] = Config.SECRET_KEY

assets = Environment(app)
assets.url = app.static_url_path
scss = Bundle('css/base.scss',
              'css/login.scss',
              'css/index.scss',
              filters='pyscss',
              output='scss/all.css')
assets.register('scss_all', scss)

from event import socketio
from routes import main

app.register_blueprint(main)

socketio.init_app(app)

if __name__ == "__main__":
    app.debug = True
    socketio.run(app)
Ejemplo n.º 51
0
application = Flask(__name__)
application.config.from_envvar('APP_CONFIG')
application.json_encoder = AlchemyEncoder
application.cache = RedisCache(application.config['REDIS_HOST'],
                               application.config['REDIS_PORT'], \
                               default_timeout=application.config['CACHE_TIMEOUT'])
application.cache_lock = Lock(application.cache._client,
                              'mgtrk_worker_lock',
                              timeout=0.2,
                              blocking_timeout=0.2)

# set up authentication
bcrypt = Bcrypt(application)

# bundle js and css code
assets = Environment(application)

js = Bundle('js/core/*', filters='rjsmin', output='js/core/mgtrk-core.min.js')
assets.register('core-js', js)

css = Bundle('css/core/*',
             filters='cssmin',
             output='css/core/mgtrk-core.min.css')
assets.register('core-css', css)

# switch off bundling if app is in debug mode
assets.debug = application.config['FLASK_DEBUG']

# set up database
db = SQLAlchemy()
db.init_app(application)
Ejemplo n.º 52
0
from flask_cache import Cache
from flask_debugtoolbar import DebugToolbarExtension
from flask_login import LoginManager
from flask_assets import Environment

from gordon_cole_gen.models import User

# Setup flask cache
cache = Cache()

# init flask assets
assets_env = Environment()

debug_toolbar = DebugToolbarExtension()

login_manager = LoginManager()
login_manager.login_view = "main.login"
login_manager.login_message_category = "warning"


@login_manager.user_loader
def load_user(userid):
    return User.query.get(userid)
Ejemplo n.º 53
0
from flask_assets import Environment, Bundle
from flask import current_app as app

assets = Environment(app)
Environment.auto_build = True
Environment.debug = False
less_bundle = Bundle('less/*.less',
                     filters='less,cssmin',
                     output='dist/css/styles.css',
                     extra={'rel': 'stylesheet/less'})
js_bundle = Bundle('js/*.js', filters='jsmin', output='dist/js/main.js')
assets.register('less_all', less_bundle)
assets.register('js_all', js_bundle)
if app.config['FLASK_ENV'] == 'development':
    less_bundle.build(force=True)
    js_bundle.build()
Ejemplo n.º 54
0
import sys
import os

from flask_assets import Environment, Bundle
from sass import compile as sass_compile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/../../')

from amable import app


# Helper so we don't have to write out the assets path over and over
def assets_path(*paths):
    return os.path.join(os.path.dirname(__file__), '..', 'static', *paths)


# Create a new assets environment attached to our app
assets_env = Environment(app)

# Tell assets where our assets are located
assets_env.load_path = [assets_path('css'), assets_path('jsc')]

# Register the CSS assets
assets_env.register(
    'css', Bundle('application.css', filters=[], output='application.css'))

# Resgister the JS assets
assets_env.register(
    'jsc', Bundle('application.js', filters=[], output='application.js'))
Ejemplo n.º 55
0
    app.secret_key = serverParameters["_secretKey"]
else:
    # Set a temporary secret key. It can be set from the database later
    # The production key is set in ``overwatch.webApp.run``
    app.secret_key = str(os.urandom(50))

# Enable debugging if set in configuration
if serverParameters["debug"] is True:
    app.debug = True

# Setup Bcrypt
app.config["BCRYPT_LOG_ROUNDS"] = config.bcryptLogRounds
bcrypt = Bcrypt(app)

# Setup flask assets
assets = Environment(app)
# Set the Flask Assets debug mode
# Note that the bundling is _only_ performed when flask assets is _not_ in debug mode.
# Thus, we want it to follow the global debug setting unless we explicit set it otherwise.
# For more information, particularly on debugging, see the web app `README.md`. Further details
# are included in the web app utilities module where the filter is defined.
app.config["ASSETS_DEBUG"] = serverParameters[
    "flaskAssetsDebug"] if not serverParameters[
        "flaskAssetsDebug"] is None else serverParameters["debug"]
# Load bundles from configuration file
assets.from_yaml(
    pkg_resources.resource_filename("overwatch.webApp", "flaskAssets.yaml"))

# Setup CSRF protection via flask-wtf
csrf = CSRFProtect(app)
Ejemplo n.º 56
0
from arxivdigest.frontend.views import topics
from arxivdigest.frontend.views.articles import topic_flag

app = Flask(__name__)
app.secret_key = secret_key
app.register_blueprint(general.mod)
app.register_blueprint(articles.mod)
app.register_blueprint(evaluation.mod)
app.register_blueprint(admin.mod, url_prefix='/admin')
app.config['max_content_length'] = config_frontend.get('max_content_length')

if topic_flag:
    app.register_blueprint(topics.mod)

csrf = CSRFProtect(app)
assets = Environment(app)
if config_frontend.get('data_path', None):
    data_path = config_frontend['data_path']
    cache_path = os.path.join(data_path, 'cache', '.webassets-cache')
    static_path = os.path.abspath(os.path.join(data_path, 'static'))

    pathlib.Path(cache_path).mkdir(parents=True, exist_ok=True)

    assets.cache = os.path.abspath(cache_path)
    assets.directory = os.path.abspath(static_path)
    app.static_folder = static_path

    if os.path.exists(static_path):
        shutil.rmtree(static_path)
    shutil.copytree(os.path.join(app.root_path, 'static'), static_path)
Ejemplo n.º 57
0
                    "utm_medium": "email",
                    "utm_source": "transactional",
                    "utm_campaign": "user-account"
                }
            }
        }
    }
    message.extra_headers = {'X-SMTPAPI': json.dumps(extra_headers)}
    original_send(message)


app.extensions.get('mail').send = send_email_with_sendgrid

# setup assets
from flask_assets import Environment, Bundle
assets = Environment(app)
assets.url_expire = False
assets.debug = app.debug
# source files
assets.load_path = ['%s/static' % app.config.root_path]

from webassets.filter.pyscss import PyScss

assets.register(
    'css',
    Bundle('font-awesome-4.7.0/css/font-awesome.min.css',
           'chosen/chosen.min.css',
           'resources/css/review.css',
           Bundle('resources/css/style.scss',
                  'resources/css/bill-progress.scss',
                  'resources/css/bootstrap-sortable.css',
Ejemplo n.º 58
0
    filters="jsmin",
)
js_footer = Bundle("js/main.js",
                   "js/map.js",
                   output="assets/footer.js",
                   filters="jsmin")
css = Bundle(
    "node_modules/bulma/css/bulma.css",
    "node_modules/leaflet/dist/leaflet.css",
    "node_modules/leaflet.control.layers.tree/L.Control.Layers.Tree.css",
    "css/style.css",
    output="assets/main.css",
    filters="cssmin",
)

assets = Environment(app)
client = MongoClient(settings.uri)

assets.register("head_js", js_head)
assets.register("head_def_js", js_head_defer)
assets.register("footer_js", js_footer)
assets.register("main_css", css)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/table")
def table():
Ejemplo n.º 59
0
def init(app):
    assets = Environment(app)

    # Basic CSS and Javascript:
    # Available under: base_css, base_js
    base_css = Bundle(
        "css/base.scss", filters="pyscss,cssmin", output="gen/css/base.%(version)s.css"
    )
    base_js = Bundle(
        "scripts/base.js", filters="jsmin", output="gen/scripts/base.%(version)s.js"
    )
    assets.register("base_css", base_css)
    assets.register("base_js", base_js)

    datetime_js = Bundle(
        "scripts/datetime.js",
        filters="jsmin",
        output="gen/scripts/datetime.%(version)s.js",
    )
    assets.register("datetime", datetime_js)

    # Admin site
    # Availabe under: admin_create_banphrase, admin_create_command,
    #                 admin_create_row, admin_edit_command
    admin_create_banphrase = Bundle(
        "scripts/admin/create_banphrase.js",
        filters="jsmin",
        output="gen/scripts/admin/create_banphrase.%(version)s.js",
    )
    admin_create_command = Bundle(
        "scripts/admin/create_command.js",
        filters="jsmin",
        output="gen/scripts/admin/create_command.%(version)s.js",
    )
    admin_create_row = Bundle(
        "scripts/admin/create_row.js",
        filters="jsmin",
        output="gen/scripts/admin/create_row.%(version)s.js",
    )
    admin_edit_command = Bundle(
        "scripts/admin/edit_command.js",
        filters="jsmin",
        output="gen/scripts/admin/edit_command.%(version)s.js",
    )
    assets.register("admin_create_banphrase", admin_create_banphrase)
    assets.register("admin_create_command", admin_create_command)
    assets.register("admin_create_row", admin_create_row)
    assets.register("admin_edit_command", admin_edit_command)

    notifications_subscribers = Bundle(
        "scripts/notifications/subscribers.js",
        filters="jsmin",
        output="gen/scripts/notifications/subscribers.%(version)s.js",
    )
    assets.register("notifications_subscribers", notifications_subscribers)

    # Third party libraries
    # Available under: autolinker
    autolinker = Bundle(
        "scripts/autolinker.js",
        filters="jsmin",
        output="gen/scripts/autolinker.%(version)s.js",
    )
    assets.register("autolinker", autolinker)

    # Commands
    # Available under: commands_js
    commands_js = Bundle(
        "scripts/commands.js",
        filters="jsmin",
        output="gen/scripts/commands.%(version)s.js",
    )
    assets.register("commands_js", commands_js)

    # Pagination script
    # Available under: paginate_js
    paginate_js = Bundle(
        "scripts/paginate.js",
        filters="jsmin",
        output="gen/scripts/paginate.%(version)s.js",
    )
    assets.register("paginate_js", paginate_js)

    # range slider for semantic UI
    range_slider_js = Bundle(
        "scripts/range.js", filters="jsmin", output="gen/scripts/range.%(version)s.js"
    )
    assets.register("range_slider_js", range_slider_js)
    range_slider_css = Bundle(
        "css/range.css", filters="cssmin", output="gen/css/range.%(version)s.css"
    )
    assets.register("range_slider_css", range_slider_css)

    assets.init_app(app)
Ejemplo n.º 60
0
def create_app(config):
    app = Flask(__name__)
    config_name = config
    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')
    app.config.from_object(Config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # Connected to Azure database
    if os.getenv('SHOULD_USE_AZURE'):
        param_string = "DRIVER={};SERVER={};DATABASE={};UID={};PWD={}".format(
            os.getenv('SQL_SERVER') or "{SQL Server}",
            os.getenv('AZURE_SERVER'), os.getenv('AZURE_DATABASE'),
            os.getenv('AZURE_USERNAME'), os.getenv('AZURE_PASS'))
        params = urllib.parse.quote_plus(param_string)
        app.config[
            'SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc:///?odbc_connect=%s" % params

    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    # not using sqlalchemy event system, hence disabling it

    Config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .room_request import room_request as room_request_blueprint
    app.register_blueprint(room_request_blueprint, url_prefix='/room-request')

    from .staff import staff as staff_blueprint
    app.register_blueprint(staff_blueprint, url_prefix='/staff')

    db.app = app

    return app