Example #1
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('css_all', css_all)
    webassets.register('js_vendor', js_vendor)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Example #2
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('apollo_css', apollo_css)
    webassets.register('apollo_js', apollo_js)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Example #3
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('css_all', css_all)
    webassets.register('js_vendor', js_vendor)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Example #4
0
def create_app():
    app = Flask(__name__,\
                static_folder="static/",\
                template_folder="templates/",\
                static_url_path="/static")

    # set config
    #    app_settings = os.getenv('APP_SETTINGS', 'app.config.DevelopmentConfig')
    app.config.from_object('config')

    # set up extensions
    db.init_app(app)

    app.register_blueprint(charts_blueprint)
    app.register_blueprint(webapi)

    # Scss
    assets = Environment(app)
    assets.versions = 'timestamp'
    assets.url_expire = True
    assets.manifest = 'file:/tmp/manifest.to-be-deployed'  # explict filename
    assets.cache = False
    assets.auto_build = True

    assets.url = app.static_url_path
    scss = Bundle('scss/__main__.scss',
                  filters='pyscss',
                  output='css/main.css',
                  depends=['scss/*.scss'])
    assets.register('scss_all', scss)

    assets.debug = False
    app.config['ASSETS_DEBUG'] = False

    return app
Example #5
0
def create_app():
    app = Flask(__name__,\
                static_folder="static/",\
                template_folder="templates/",\
                static_url_path="/static")

    set_config(app)

    # set up extensions
    cache.init_app(app)
    db.init_app(app)
    datepicker(app)
    mail.init_app(app)

    # blueprints
    app.register_blueprint(auth)
    app.register_blueprint(admin_blueprint)
    app.register_blueprint(charts_blueprint)
    app.register_blueprint(webapi)
    app.register_blueprint(monitor_blueprint)

    # login_manager
    login_manager = LoginManager()
    login_manager.login_view = 'charts.now'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))

    # form csrf
    csrf.init_app(app)

    # Scss
    assets = Environment(app)
    assets.versions = 'timestamp'
    assets.url_expire = True
    assets.manifest = 'file:/tmp/manifest.to-be-deployed'  # explict filename
    assets.cache = False
    assets.auto_build = True

    assets.url = app.static_url_path
    scss = Bundle('scss/__main__.scss',
                  filters='pyscss',
                  output='css/main.css',
                  depends=['scss/*.scss'])
    assets.register('scss_all', scss)

    assets.debug = False
    app.config['ASSETS_DEBUG'] = False

    with app.app_context():
        init_db_admin_config()

    toolbar = DebugToolbarExtension(app)
    return (app)
Example #6
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('css_all', css_all)
    # webassets.register('js_quote', js_quote)
    # webassets.register('js_main', js_customer)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Example #7
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
Example #8
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
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
Example #10
0
def create_app():
    """ Create a HubGrep Flask-app. """
    app = Flask(__name__, static_url_path="/static", static_folder="static")
    assets = Environment(app)

    # disable cache, because that breaks
    # prod build for some reason.
    # maybe add to the flask config?
    assets.cache = False
    assets.manifest = False

    @app.after_request
    def add_gnu_tp_header(response):
        # www.gnuterrypratchett.com
        response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
        return response

    config_mapping = {
        constants.APP_ENV_BUILD: "hubgrep.config.BuildConfig",
        constants.APP_ENV_DEVELOPMENT: "hubgrep.config.DevelopmentConfig",
        constants.APP_ENV_PRODUCTION: "hubgrep.config.ProductionConfig",
        constants.APP_ENV_TESTING: "hubgrep.config.TestingConfig",
    }
    app_env = os.environ.get("APP_ENV", constants.APP_ENV_DEVELOPMENT)
    print(f"starting in {app_env} config")
    app.config.from_object(config_mapping[app_env])

    if app.config['WATCH_SCSS']:
        app.wsgi_app = SassMiddleware(app.wsgi_app, app.config["SASS_MANIFEST"])

    babel = Babel(app)

    init_logging(loglevel=app.config["LOGLEVEL"])

    db.init_app(app)
    migrate.init_app(app, db=db)

    from hubgrep.frontend_blueprint import frontend
    from hubgrep.cli_blueprint import cli_bp

    app.register_blueprint(frontend)
    app.register_blueprint(cli_bp)

    @babel.localeselector
    def get_locale():
        lang = request.accept_languages.best_match(app.config["LANGUAGES"].keys())
        return lang

    app.jinja_env.globals["get_locale"] = get_locale
    app.jinja_env.globals["constants"] = constants
    app.jinja_env.globals["timeago"] = timeago
    app.jinja_env.globals["datetime_now"] = datetime.datetime.now()
    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    return app
Example #11
0
def init_app(app):
    """
    Initilize assets.
    :param app:
    """
    if app.debug:
        webassets = Environment(app)
        webassets.url = app.static_url_path
        webassets.register('css_all', css_all)
        webassets.manifest = False
        webassets.cache = False
        webassets.debug = False
        webassets.cache = not app.debug
        webassets.debug = app.debug
        log = logging.getLogger('webassets')
        log.addHandler(logging.StreamHandler())
        log.setLevel(logging.DEBUG)
        cmdenv = CommandLineEnvironment(webassets, log)
        cmdenv.build()
Example #12
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('css_all', css_all)
    webassets.register('js_angular', js_angular)
    webassets.register('js_foundation', js_foundation)
    webassets.register('js_vendor', js_vendor)
    webassets.register('js_d3', js_d3)
    webassets.register('js_main', js_main)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
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
Example #14
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
Example #15
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('css_cover', css_cover)
    webassets.register('css_auth', css_auth)
    webassets.register('css_fancybox', css_fancybox)
    webassets.register('css_all', css_base)
    webassets.register('js_comment', js_comment)
    webassets.register('js_all', js_base)
    webassets.register('js_fancybox', js_fancybox)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Example #16
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
Example #17
0
def init_app(app):
    debug = app.debug
    webassets = Environment(app)
    # add foundation sass files to sass compiler paths
    webassets.config['SASS_LOAD_PATHS'] = ["../bower_components/foundation/scss/",
                                           "."]

    webassets.register('css_kb', css_kb)
    webassets.register('shivs', shivs)
    webassets.register('js_vendor', js_vendor)
    webassets.register('js_main', js_main)


    webassets.manifest = 'cache' if not debug else False
    webassets.cache = not debug
    webassets.debug = debug
Example #18
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.')
Example #19
0
db = SQLAlchemy(app)
migrate = Migrate(app, db)

# Initiate Flask Login to handle
# authentication and redirects for
# Un logged in users.
login = LoginManager(app)
login.login_view = 'index'

# Flask Assets handles bundling our
# CSS and JavaScript files into a
# single minified file when we are
# not in development mode.
assets = Environment(app)
assets.debug = Config.DEBUG
assets.cache = not Config.DEBUG
assets.url_expire = Config.DEBUG

# Database Models, and Routes must
# be imported after the app object
# is defined.
from app import models, routes

# Define our bundlels for Flask Assets.
# These will be used by our base.html
# template.
routes.make_asset_bundles()

# Run our Flask app when this file is
# invoked directly. This happens when
# gunicorn first calls our app package.
def create_app(config_name=None):
    csp_policy = copy.deepcopy(CSP_POLICY)
    app = Flask(__name__)

    app_config = f'config.{config_name or os.environ.get("APP_SETTINGS", "Config")}'
    app.config.from_object(app_config)

    if Config.WTF_CSRF_ENABLED:
        Talisman(
            app,
            content_security_policy=csp_policy,
            content_security_policy_nonce_in=['script-src'],
            force_https=False,  # this is handled at the load balancer
            legacy_content_security_policy_header=True,
            strict_transport_security=True,
            strict_transport_security_max_age=ONE_YEAR_IN_SECONDS,
            referrer_policy=DEFAULT_REFERRER_POLICY,
            frame_options='SAMEORIGIN',
            frame_options_allow_from=None,
            session_cookie_secure=True,
            session_cookie_http_only=True)
    app.name = "response_operations_ui"

    CSRFProtect(app)

    # Load css and js assets
    assets = Environment(app)

    if app.config['DEBUG'] or app.config['TESTING']:
        assets.cache = False
        assets.manifest = None

    if not app.config['DEBUG']:
        app.wsgi_app = GCPLoadBalancer(app.wsgi_app)

    assets.url = app.static_url_path

    app.jinja_env.add_extension('jinja2.ext.do')

    app.register_blueprint(filter_blueprint)

    app.url_map.strict_slashes = False
    app.secret_key = app.config['RESPONSE_OPERATIONS_UI_SECRET']

    logger_initial_config(service_name='response-operations-ui', log_level=app.config['LOGGING_LEVEL'])
    logger = wrap_logger(logging.getLogger(__name__))
    logger.info('Logger created', log_level=app.config['LOGGING_LEVEL'])

    login_manager = LoginManager(app)
    login_manager.init_app(app)
    login_manager.login_view = "sign_in_bp.sign_in"

    @app.context_processor
    def inject_availability_message():

        redis_avail_msg = app.config['SESSION_REDIS']

        if len(redis_avail_msg.keys('AVAILABILITY_MESSAGE_RES_OPS')) == 1:
            return {
                "availability_message": redis_avail_msg.get('AVAILABILITY_MESSAGE_RES_OPS').decode('utf-8')
            }
        return {}

    @login_manager.user_loader
    def user_loader(user_id):
        username = session.get('username')
        return User(user_id, username)

    # wrap in the flask server side session manager and back it by redis
    app.config['SESSION_REDIS'] = redis.StrictRedis(host=app.config['REDIS_HOST'],
                                                    port=app.config['REDIS_PORT'],
                                                    db=app.config['REDIS_DB'])

    app.jinja_environment.lstrip_blocks = True

    if app.config['DEBUG'] or os.environ.get('JINJA_RELOAD'):
        app.jinja_env.auto_reload = True

    Session(app)

    setup_blueprints(app)

    return app
Example #21
0
from flask import Flask, render_template
from flask_assets import Environment, Bundle
from flask_frozen import Freezer


SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

app = Flask(
    import_name=__name__,
    static_folder=os.path.join(SITE_ROOT, '..', '..', 'static'),
    template_folder=os.path.join(SITE_ROOT, '..', '..', 'templates'),
)

assets = Environment(app)
assets.manifest = False
assets.cache = False
assets.debug = True

freezer = Freezer(app)

app.config.update(
    DEBUG=True,
    FREEZER_DESTINATION=os.path.join(SITE_ROOT, '..', '..', 'build')
)


assets.register('js_all', Bundle(
    'js/website.js',
    filters='jsmin',
    output='build/website.js'
))
])
app.jinja_loader = my_loader

db = SQLAlchemy(app)

Markdown(app, extensions=['footnotes'])
pages = FlatPages(app)

manager = Manager(app)

# Scss
assets = Environment(app)
assets.url_expire = True
assets.auto_build = True
assets.append_path('sni/assets')
assets.cache = 'sni/assets/.webassets-cache'

scss = Bundle('scss/__main__.scss', filters='pyscss', output='css/main.css',
              depends=['scss/*.scss'])
assets.register('scss_all', scss)

assets.debug = False
app.config['ASSETS_DEBUG'] = False

cache = Cache(app, config={'CACHE_TYPE': 'simple'})

if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler('tmp/snilog.csv',
                                       'a',
Example #23
0
def compile_assets(app):
    assets = Environment(app)

    js = Bundle(
        'js/*.js',  # 'home_bp/js/*.js', 'admin_bp/js/*.js',
        filters='jsmin',
        output='gen/packed.js')
    css = Bundle('css/*.css',
                 'css/dash/*.css',
                 'home_bp/css/*.css',
                 'admin_bp/css/*.css',
                 'auth_bp/css/*.css',
                 'shopping_add_bp/css/*.css',
                 'shopping_view_bp/css/*.css',
                 filters='cssmin',
                 output='gen/packed.css')
    jquery = Bundle('js/jquery/jquery.min.js',
                    filters='jsmin',
                    output='gen/jquery.js')
    chosen_css = Bundle('css/chosen/chosen.min.css',
                        filters='cssmin',
                        output='gen/chosen.css')
    chosen_js = Bundle('js/chosen/chosen.jquery.js',
                       filters='jsmin',
                       output='gen/chosen.js')
    jrange_css = Bundle('css/jrange/jquery.range.css',
                        filters='cssmin',
                        output='gen/jrange.css')
    jrange_js = Bundle('js/jrange/jquery.range.js',
                       filters='jsmin',
                       output='gen/jrange.js')
    datatables_css = Bundle('css/datatables/jquery.dataTables.css',
                            'css/datatables/jquery.dataTables_OVERRIDES.css',
                            filters='cssmin',
                            output='gen/datatables.css')
    datatables_js = Bundle('js/datatables/jquery.dataTables.js',
                           filters='jsmin',
                           output='gen/datatables.js')
    daterangepicker_css = Bundle('css/daterangepicker/daterangepicker.css',
                                 filters='cssmin',
                                 output='gen/daterangepicker.css')
    daterangepicker_js = Bundle('js/daterangepicker/moment.min.js',
                                'js/daterangepicker/daterangepicker.js',
                                filters='jsmin',
                                output='gen/daterangepicker.js')
    flexdatalist_css = Bundle('css/flexdatalist/jquery.flexdatalist.css',
                              filters='cssmin',
                              output='gen/flexdatalist.css')
    flexdatalist_js = Bundle('js/flexdatalist/jquery.flexdatalist.js',
                             filters='jsmin',
                             output='gen/flexdatalist.js')
    jquerymodal_css = Bundle('css/jquerymodal/jquery.modal.min.css',
                             filters='cssmin',
                             output='gen/jquerymodal.css')
    jquerymodal_js = Bundle('js/jquerymodal/jquery.modal.min.js',
                            filters='jsmin',
                            output='gen/jquerymodal.js')

    plotly_js = Bundle('js/plotly/plotly.basic.js',
                       filters='jsmin',
                       output='gen/plotly.js')

    bundles = {
        'js_all': js,
        'css_all': css,
        'chosen_css': chosen_css,
        'chosen_js': chosen_js,
        'jrange_css': jrange_css,
        'jrange_js': jrange_js,
        'jquery': jquery,
        'datatables_js': datatables_js,
        'datatables_css': datatables_css,
        'daterangepicker_js': daterangepicker_js,
        'daterangepicker_css': daterangepicker_css,
        'flexdatalist_js': flexdatalist_js,
        'flexdatalist_css': flexdatalist_css,
        'jquerymodal_js': jquerymodal_js,
        'jquerymodal_css': jquerymodal_css,
        'plotly_js': plotly_js,
    }

    # selinux prevents flask-assets to dynamically build/access cached files
    if app.config['DISABLE_CACHE']:
        assets.cache = False
        assets.manifest = False

    assets.register(bundles)
    # assets.register('css_all', css)
    return assets
Example #24
0
def create_app(config_name=None):
    csp_policy = copy.deepcopy(CSP_POLICY)
    app = Flask(__name__)

    app_config = f'config.{config_name or os.environ.get("APP_SETTINGS", "Config")}'
    app.config.from_object(app_config)

    if Config.WTF_CSRF_ENABLED:
        Talisman(
            app,
            content_security_policy=csp_policy,
            content_security_policy_nonce_in=["script-src"],
            force_https=False,  # this is handled at the load balancer
            strict_transport_security=True,
            strict_transport_security_max_age=ONE_YEAR_IN_SECONDS,
            referrer_policy=DEFAULT_REFERRER_POLICY,
            frame_options="SAMEORIGIN",
            frame_options_allow_from=None,
            session_cookie_secure=True,
            session_cookie_http_only=True,
        )
    app.name = "response_operations_ui"

    csrf = CSRFProtect(app)

    # Load css and js assets
    assets = Environment(app)

    if app.config["DEBUG"] or app.config["TESTING"]:
        assets.cache = False
        assets.manifest = None

    if not app.config["DEBUG"]:
        app.wsgi_app = GCPLoadBalancer(app.wsgi_app)

    assets.url = app.static_url_path

    app.jinja_env.add_extension("jinja2.ext.do")
    app.jinja_env.globals["hasPermission"] = user_has_permission

    app.register_blueprint(filter_blueprint)

    app.url_map.strict_slashes = False
    app.secret_key = app.config["RESPONSE_OPERATIONS_UI_SECRET"]

    logger_initial_config(service_name="response-operations-ui",
                          log_level=app.config["LOGGING_LEVEL"])
    logger = wrap_logger(logging.getLogger(__name__))
    logger.info("Logger created", log_level=app.config["LOGGING_LEVEL"])

    login_manager = LoginManager(app)
    login_manager.init_app(app)
    login_manager.login_view = "sign_in_bp.sign_in"

    @app.errorhandler(CSRFError)
    def handle_csrf_error(e):
        flash("Your session timed out", category="info")
        return redirect(url_for("logout_bp.logout"))

    @app.before_request
    def before_request():

        session.permanent = True  # set session to use PERMANENT_SESSION_LIFETIME
        session.modified = True  # reset the session timer on every request
        try:
            csrf.protect()

        except Exception as e:
            if e.code == 400:
                logger.warning(e.description)
            logger.warning(e)

    @app.context_processor
    def inject_availability_message():

        redis_avail_msg = app.config["SESSION_REDIS"]

        if len(redis_avail_msg.keys("AVAILABILITY_MESSAGE_RES_OPS")) == 1:
            return {
                "availability_message":
                redis_avail_msg.get("AVAILABILITY_MESSAGE_RES_OPS").decode(
                    "utf-8")
            }
        return {}

    @login_manager.user_loader
    def user_loader(user_id):
        username = session.get("username")
        return User(user_id, username)

    # wrap in the flask server side session manager and back it by redis
    app.config["SESSION_REDIS"] = redis.StrictRedis(
        host=app.config["REDIS_HOST"],
        port=app.config["REDIS_PORT"],
        db=app.config["REDIS_DB"])

    app.jinja_environment.lstrip_blocks = True

    if app.config["DEBUG"] or os.environ.get("JINJA_RELOAD"):
        app.jinja_env.auto_reload = True

    Session(app)

    setup_blueprints(app)

    return app
])
app.jinja_loader = my_loader

db = SQLAlchemy(app)

Markdown(app, extensions=['footnotes'])
pages = FlatPages(app)

manager = Manager(app)

# Scss
assets = Environment(app)
assets.url_expire = True
assets.auto_build = True
assets.append_path('sni/assets')
assets.cache = 'sni/assets/.webassets-cache'

scss = Bundle('scss/__main__.scss',
              filters='pyscss',
              output='css/main.css',
              depends=['scss/*.scss'])
assets.register('scss_all', scss)

assets.debug = False
app.config['ASSETS_DEBUG'] = False

cache = Cache(app, config={'CACHE_TYPE': 'simple'})

if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
Example #26
0
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)

# Do not automatically build assets in deployment for performance
assets.auto_build = False
assets.append_path(os.path.join(app.root_path, 'uncompiled_assets'))

js_bundle = Bundle('javascript/autocomplete.js',
                   'javascript/evaluation.js',
                   'javascript/utils.js',
                   'javascript/forms.js',
Example #27
0
import os
from flask_assets import Bundle, Environment
from . import app

# Assets
webassets = Environment(app)
webassets.load_path = [
    os.path.join(os.path.dirname(__file__), "static"),
    os.path.join(os.path.dirname(__file__), "bower_components")
]
webassets.manifest = 'cache' if not app.debug else False
webassets.cache = not app.debug
webassets.debug = True  # app.debug

js_main = Bundle("js/src/main.js", output="js/main.js")

css_main = Bundle("css/src/styles.css", output="css/main.css")

js_libs = Bundle("jquery/dist/jquery.min.js",
                 "semantic-ui/dist/semantic.min.js",
                 output="js/libs.js")

css_libs = Bundle("font-awesome/web-fonts-with-css/css/fontawesome.min.css",
                  "semantic-ui/dist/semantic.min.css",
                  output="css/libs.css")

webassets.register('js_main', js_main)
webassets.register('js_libs', js_libs)
webassets.register('css_main', css_main)
webassets.register('css_libs', css_libs)
Example #28
0
application = Flask(__name__,\
                    static_folder="platus/static/",\
                     template_folder="platus/templates/",
                    static_url_path="/static")
application.register_blueprint(web)
application.register_blueprint(api)

application.config.update(config.from_yaml("data/config.yaml"))

# Scss
assets = Environment(application)
assets.versions = 'timestamp'
assets.url_expire = True
assets.manifest = 'file:/tmp/manifest.to-be-deployed'  # explict filename
assets.cache = False
assets.auto_build = True

assets.url = application.static_url_path
scss = Bundle('scss/00_main.scss',
              filters='pyscss',
              output='css/main.css',
              depends=['scss/*.scss'])
assets.register('scss_all', scss)

assets.debug = False
application.config['ASSETS_DEBUG'] = False

# Set Logger
log_levels = {
    "info": logging.INFO,
Example #29
0
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
# LESS_BIN = os.path.join(SCRIPT_ROOT, '..', 'node_modules', 'less', 'bin', 'lessc')
LESS_LINE_NUMBERS = 'mediaquery'
FREEZER_DESTINATION = os.path.join(SITE_ROOT, '..', '..', 'build')
FLATPAGES_ROOT = os.path.join(SITE_ROOT, '..', '..', 'pages')

app = Flask(
    import_name='codingnotes',
    static_folder=os.path.join(SITE_ROOT, '..', '..', 'static'),
    template_folder=os.path.join(SITE_ROOT, '..', '..', 'templates'),
)

assets = Environment(app)
assets.manifest = False
assets.cache = False
if DEBUG:
    assets.manifest = False
    assets.cache = None
freezer = Freezer(app)
pages_on_disk = FlatPages(app)

app.config.from_object(__name__)


def is_published(post_date):
    return utc.localize(datetime.utcnow()) >= utc.localize(datetime.combine(post_date, time(0, 0, 0)))
published_pages = sorted([p for p in pages_on_disk if is_published(p.meta.get('date', '2099-12-31'))], key=lambda p: p.meta['date'])


def get_latest_pages(limit=10):
Example #30
0
def run(datapath):
    """
    starts the frontend server
    datapath: directory for saving and loading requirement projects
    """

    with open(join(dirname(dirname(__file__)), 'VERSION'),
              mode='r') as version_file:
        stlinspector_version = version_file.read()

    app = Flask(__name__)

    # interface to the projects and backend
    projectList = ProjectList(datapath)

    # temporal directory for caching etc.
    tempDir = mkdtemp(prefix="STLInspector")

    # Bundle the javascript files into one distribution file
    # and the css file such that it is reloaded on a change
    bundles = {
        'STLInspector_js':
        Bundle('js/AlertView.js',
               'js/BooleanChart.js',
               'js/Project.js',
               'js/Projects.js',
               'js/ProjectsView.js',
               'js/ProjectView.js',
               'js/RealChart.js',
               'js/ServerRequest.js',
               'js/SignalView.js',
               'js/STLInspector.js',
               output='build/STLInspector.js'),
        'STLInspector_css':
        Bundle('css/STLInspector.css', output='build/STLInspector.css')
    }
    assets = Environment(app)
    assetscachepath = join(tempDir, 'assetscache')
    # create directory if not already present
    if not access(assetscachepath, F_OK):
        mkdir(assetscachepath)
    assets.cache = assetscachepath

    assetsdirectorypath = join(tempDir, 'assetsdirectory')
    # create directory if not already present
    if not access(assetsdirectorypath, F_OK):
        mkdir(assetsdirectorypath)
    assets.directory = assetsdirectorypath

    assets.register(bundles)

    @app.route("/")
    def index():
        """index page loader

        loads and renders the index template
        """
        return render_template('index.html',
                               stlinspector_version=stlinspector_version)

    @app.route('/static/build/<path:filename>')
    def static_build_files(filename):
        """
        serve static build files from cache directory
        """
        return send_from_directory(join(assetsdirectorypath, 'build'),
                                   filename)

    @app.route("/documentation/")
    def documentation():
        """renders the documentation page"""
        fdoc = open(join(dirname(dirname(__file__)), "doc/documentation.md"),
                    "r")
        doc = markdown.Markdown(extensions=['mdx_math'],
                                extension_configs={
                                    'mdx_math': {
                                        'enable_dollar_delimiter': True
                                    }
                                }).convert(fdoc.read())
        fdoc.close()
        return render_template('documentation.html', doctext=Markup(doc))

    @app.route('/documentation/images/<path:filename>')
    def documentation_images(filename):
        return send_from_directory('../doc/images', filename)

    @app.route("/api/projects/list", methods=['POST'])
    def api_projects_list():
        """project list loader"""

        try:
            return Response(json.dumps(projectList.list()),
                            mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/projects/create", methods=['POST'])
    def api_projects_create():
        """create a project with given name"""

        try:
            projectTitle = request.form['title']
            return Response(json.dumps(projectList.create(projectTitle)),
                            mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/projects/delete", methods=['POST'])
    def api_projects_delete():
        """deletes the project file"""

        try:
            projectId = request.form['id']
            projectList.delete(projectId)
            return Response('true', mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/project/save", methods=['POST'])
    def api_project_save():
        """saves the project to file"""

        try:
            projectId = request.form['id']
            projectList.saveProject(projectId)
            return Response('true', mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/project/close", methods=['POST'])
    def api_project_close():
        """is called when a project is closed in the frontend"""

        try:
            projectId = request.form['id']
            projectList.close(projectId)
            return Response('true', mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/project/load", methods=['POST'])
    def api_project_load():
        """returns the data of a project with the given id"""

        try:
            projectId = request.form['id']
            project = projectList.project(projectId)
            return Response(json.dumps(project.state()),
                            mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/project/change", methods=['POST'])
    def api_project_change():
        """changes project variables"""

        try:
            projectId = request.form['id']
            project = projectList.project(projectId)
            if 'stlCandidate' in request.form:
                project.setStlCandidate(request.form['stlCandidate'])
            if 'textRequirement' in request.form:
                project.setTextRequirement(request.form['textRequirement'])
            if 'textNotes' in request.form:
                project.setTextNotes(request.form['textNotes'])
            return Response('true', mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/project/test", methods=['POST'])
    def api_project_test():
        """returns an existing or new test signal"""

        try:
            projectId = request.form['id']
            test_type = request.form['type']
            parameter = request.form['parameter']
            project = projectList.project(projectId)
            if test_type == 'evaluate':
                test = project.testForName(parameter)
            else:
                test = project.testById(int(parameter))
            return Response(json.dumps(test), mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    @app.route("/api/project/testEvaluation", methods=['POST'])
    def api_project_testEvaluation():
        """returns an existing or new test signal"""

        try:
            projectId = request.form['id']
            testId = int(request.form['testId'])
            username = request.form['username']
            evaluation = request.form['evaluation'] == 'true'
            project = projectList.project(projectId)
            project.setTestEvaluation(testId, username, evaluation)
            return Response('true', mimetype='application/json')
        except Exception as e:
            exceptionHandler(e)
            abort(500)

    webbrowser.open_new_tab('http://localhost:{}'.format(PORT))
    app.run(debug=False, port=PORT)
Example #31
0
def setup_assets(app):
    assets = Environment(app)
    assets.url_expire = True

    assets.cache = False
    assets.manifest = False
    assets.load_path = [
        os.path.join(app.config['PROJECT_ROOT'], 'static'),
        os.path.join(app.config['PROJECT_ROOT'], 'bower_components')
    ]

    css_main = Bundle(
        'bootstrap/dist/css/bootstrap.min.css',
        'bootstrap-toggle/css/bootstrap-toggle.min.css',
        'awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css',
        'datatables/media/css/jquery.dataTables.min.css',
        'datatables/media/css/dataTables.bootstrap.min.css',
        'bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css',
        'clockpicker/dist/bootstrap-clockpicker.min.css',
        'eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css',  # NOQA
        'emojione/assets/css/emojione.min.css',
        'emojionearea/dist/emojionearea.min.css',
        'js/plugins/export/export.css',
        'main.css',
        # inspinia theme files
        'inspinia_v2.7.1/css/style.css',
        'inspinia_v2.7.1/css/animate.css',
        'inspinia_v2.7.1/font-awesome/css/font-awesome.min.css',
    )
    js_main = Bundle(
        'jquery/dist/jquery.min.js',
        'jquery-ui/jquery-ui.min.js',
        'bootstrap/dist/js/bootstrap.min.js',
        'bootstrap-toggle/js/bootstrap-toggle.min.js',
        'datatables/media/js/jquery.dataTables.min.js',
        'datatables/media/js/dataTables.bootstrap.min.js',
        'moment/min/moment-with-locales.min.js',
        'bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
        'clockpicker/dist/bootstrap-clockpicker.min.js',
        'eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js',  # NOQA
        'jquery-textcomplete/dist/jquery.textcomplete.min.js',
        'emojione/lib/js/emojione.min.js',
        'emojionearea/dist/emojionearea.min.js',
        # amcharts files
        'js/amcharts.js',
        'js/serial.js',
        'js/pie.js',
        'js/plugins/export/export.min.js',
        'js/themes/light.js',
        # amcharts libs for export
        'js/plugins/export/libs/pdfmake/pdfmake.min.js',
        'js/plugins/export/libs/pdfmake/vfs_fonts.js',
        'js/plugins/export/libs/jszip/jszip.min.js',
        'js/plugins/export/libs/fabric.js/fabric.min.js',
        'js/plugins/export/libs/FileSaver.js/FileSaver.min.js',
        'main.js',
    )

    js_bulletin_edit = Bundle(
        js_main,
        'bulletin-edit.js'
    )

    js_story_edit = Bundle(
        js_main,
        'story-edit.js'
    )

    css_landing = Bundle(
        'landing.css',
        'emojione/assets/css/emojione.min.css',
    )

    js_landing = Bundle(
        'jquery/dist/jquery.min.js',
        'hamburger.menu.js',
        'typed.js/lib/typed.min.js',
    )

    assets.register('css_main', css_main, output='dist/css/main.css')
    assets.register('js_main', js_main, output='dist/js/main.js')

    assets.register('js_bulletin_edit', js_bulletin_edit,
                    output='dist/js/bulletin-edit.js')

    assets.register('js_story_edit', js_story_edit,
                    output='dist/js/story-edit.js')

    assets.register('css_landing', css_landing, output='dist/css/landing.css')
    assets.register('js_landing', js_landing, output='dist/js/landing.js')
Example #32
0
app.config['RECIPES_FILE'] = 'storage/data/{game_version}/recipes.json'
app.config['ESCAPISTS_WIKI_DOMAIN'] = 'theescapists.gamepedia.com'
app.config['COMPRESS_MIN_SIZE'] = 1024

cache = Cache(app)
assets = Environment(app)

if app.config['ENV'] == 'production':
    from flask_compress import Compress

    Compress(app)

if has_debug_toolbar_ext:
    toolbar = DebugToolbarExtension(app)

assets.cache = 'storage/webassets-cache/'

assets.register(
    'js_home',
    Bundle('js/common.js',
           'js/home.js',
           filters='jsmin',
           output='js/home.min.js'))
assets.register(
    'js_recipes_editor',
    Bundle('js/common.js',
           'js/recipes_editor.js',
           filters='jsmin',
           output='js/recipes_editor.min.js'))
assets.register(
    'css_app',
Example #33
0
    'tendril_css': Bundle(
        'css/tendril.css',
        output='gen/tendril.css',
        filters='cssmin'
    ),

    'nvd3_js': Bundle(
        'js/d3/d3.js',
        'js/d3/nv.d3.js',
        output='gen/nv.d3.js',
        filters='jsmin'
    ),

    'nvd3_css': Bundle(
        'css/nv.d3.css',
        output='gen/nv.d3.css',
        filters='cssmin'
    ),

    'mixer_js': Bundle(
        'js/mixer.js',
        output='gen/tendril.js',
        filters='jsmin',
    )
}


assets = Environment(app)
assets.cache = os.path.join(INSTANCE_CACHE, 'flaskassetcache')
assets.register(bundles)
FLATPAGES_EXTENSION = '.md'
# LESS_BIN = os.path.join(SCRIPT_ROOT, '..', 'node_modules', 'less', 'bin', 'lessc')
LESS_LINE_NUMBERS = 'mediaquery'
FREEZER_DESTINATION = os.path.join(SITE_ROOT, '..', '..', 'build')
FLATPAGES_ROOT = os.path.join(SITE_ROOT, '..', '..', 'pages')

app = Flask(
    import_name='codingnotes',
    static_folder=os.path.join(SITE_ROOT, '..', '..', 'static'),
    template_folder=os.path.join(SITE_ROOT, '..', '..', 'templates'),
)

assets = Environment(app)
assets.debug = DEBUG
assets.manifest = None
assets.cache = None
freezer = Freezer(app)
pages_on_disk = FlatPages(app)

app.config.from_object(__name__)


def is_published(post_date):
    return utc.localize(datetime.utcnow()) >= utc.localize(datetime.combine(post_date, time(0, 0, 0)))
published_pages = sorted([p for p in pages_on_disk if is_published(p.meta.get('date', '2099-12-31'))], key=lambda p: p.meta['date'])


def get_latest_pages(limit=10):
    pages = published_pages if not request.args.get('preview') else pages_on_disk
    # Articles are pages with a publication date
    articles = (p for p in pages if 'date' in p.meta)
Example #35
0
           'js/datatables/vfs_fonts.js',
           'js/datatables/dataTables.buttons.js',
           'js/datatables/buttons.print.js',
           'js/datatables/buttons.html5.js',
           'js/datatables/buttons.colVis.js',
           'js/datatables/buttons.foundation.js',
           'js/datatables/dataTables.select.js',
           'js/datatables/dataTables.keyTable.js',
           output='gen/datatables.js',
           filters='jsmin'),
    'tendril_css':
    Bundle('css/tendril.css', output='gen/tendril.css', filters='cssmin'),
    'nvd3_js':
    Bundle('js/d3/d3.js',
           'js/d3/nv.d3.js',
           output='gen/nv.d3.js',
           filters='jsmin'),
    'nvd3_css':
    Bundle('css/nv.d3.css', output='gen/nv.d3.css', filters='cssmin'),
    'mixer_js':
    Bundle(
        'js/mixer.js',
        output='gen/tendril.js',
        filters='jsmin',
    )
}

assets = Environment(app)
assets.cache = os.path.join(INSTANCE_CACHE, 'flaskassetcache')
assets.register(bundles)
Example #36
0
def create_app(config_filename="config"):
    """Flask application factory.

    This is the flask application factory for this project. It loads the
    other submodules used to runs the collectives website. It also creates
    the blueprins and init apps.

    :param config_filename: name of the application config file.
    :type config_filename: string

    :return: A flask application for collectives
    :rtype: :py:class:`flask.Flask`
    """
    app = Flask(__name__, instance_relative_config=True)
    app.wsgi_app = ReverseProxied(app.wsgi_app)

    # Config options - Make sure you created a 'config.py' file.
    app.config.from_object(config_filename)
    app.config.from_pyfile("config.py")
    # To get one variable, tape app.config['MY_VARIABLE']

    fileConfig(app.config["LOGGING_CONFIGURATION"],
               disable_existing_loggers=False)

    # Initialize plugins
    models.db.init_app(app)
    auth.login_manager.init_app(app)  # app is a Flask object
    api.marshmallow.init_app(app)
    profile.images.init_app(app)
    extranet.api.init_app(app)
    payline.api.init_app(app)

    app.context_processor(jinja.helpers_processor)

    _migrate = Migrate(app, models.db)

    with app.app_context():
        # Initialize asset compilation
        assets = Environment(app)

        filters = "libsass"
        if app.config["ENV"] == "production":
            filters = "libsass, cssmin"
            assets.auto_build = False
            assets.debug = False
            assets.cache = True
        else:
            assets.auto_build = True
            assets.debug = True
        scss = Bundle(
            "css/all.scss",
            filters=filters,
            depends=("/static/css/**/*.scss", "**/*.scss", "**/**/*.scss"),
            output="dist/css/all.css",
        )

        assets.register("scss_all", scss)
        if app.config["ENV"] == "production":
            scss.build()

        # Register blueprints
        app.register_blueprint(root.blueprint)
        app.register_blueprint(profile.blueprint)
        app.register_blueprint(api.blueprint)
        app.register_blueprint(administration.blueprint)
        app.register_blueprint(auth.blueprint)
        app.register_blueprint(event.blueprint)
        app.register_blueprint(payment.blueprint)
        app.register_blueprint(technician.blueprint)
        app.register_blueprint(activity_supervison.blueprint)

        # Error handling
        app.register_error_handler(werkzeug.exceptions.NotFound,
                                   error.not_found)
        app.register_error_handler(werkzeug.exceptions.InternalServerError,
                                   error.server_error)

        forms.configure_forms(app)
        forms.csrf.init_app(app)
        # Initialize DB
        # models.db.create_all()

        populate_db(app)

        return app
Example #37
0
def init_app(app):
    webassets = Environment(app)
    webassets.register('js_build', js_build)
    webassets.manifest = 'cache' if not app.debug else False
    webassets.cache = not app.debug
    webassets.debug = app.debug
Example #38
0
def create_app(config_name=None):
    app = Flask(__name__)
    app.name = "response_operations_ui"

    app_config = f'config.{config_name or os.environ.get("APP_SETTINGS", "Config")}'
    app.config.from_object(app_config)

    # Load css and js assets
    assets = Environment(app)

    if app.config['DEBUG'] or app.config['TESTING']:
        assets.cache = False
        assets.manifest = None

    assets.url = app.static_url_path

    app.jinja_env.add_extension('jinja2.ext.do')

    app.register_blueprint(filter_blueprint)

    app.url_map.strict_slashes = False
    app.secret_key = app.config['RESPONSE_OPERATIONS_UI_SECRET']

    # Zipkin
    zipkin = Zipkin(app=app, sample_rate=app.config.get("ZIPKIN_SAMPLE_RATE"))
    requestsdefaulter.default_headers(zipkin.create_http_headers_for_new_span)

    logger_initial_config(service_name='response-operations-ui',
                          log_level=app.config['LOGGING_LEVEL'])
    logger = wrap_logger(logging.getLogger(__name__))
    logger.info('Logger created', log_level=app.config['LOGGING_LEVEL'])

    login_manager = LoginManager(app)
    login_manager.init_app(app)
    login_manager.login_view = "sign_in_bp.sign_in"

    @app.context_processor
    def inject_availability_message():

        redis_avail_msg = app.config['SESSION_REDIS']

        if len(redis_avail_msg.keys('AVAILABILITY_MESSAGE_RES_OPS')) == 1:
            return {
                "availability_message":
                redis_avail_msg.get('AVAILABILITY_MESSAGE_RES_OPS').decode(
                    'utf-8')
            }
        return {}

    @login_manager.user_loader
    def user_loader(user_id):
        return User(user_id)

    if cf.detected:
        with app.app_context():
            # If deploying in cloudfoundry set config to use cf redis instance
            logger.info(
                'Cloudfoundry detected, setting service configurations')
            service = cf.redis
            app.config['REDIS_HOST'] = service.credentials['host']
            app.config['REDIS_PORT'] = service.credentials['port']

    # wrap in the flask server side session manager and back it by redis
    app.config['SESSION_REDIS'] = redis.StrictRedis(
        host=app.config['REDIS_HOST'],
        port=app.config['REDIS_PORT'],
        db=app.config['REDIS_DB'])

    app.jinja_environment.lstrip_blocks = True

    if app.config['DEBUG'] or os.environ.get('JINJA_RELOAD'):
        app.jinja_env.auto_reload = True

    Session(app)

    setup_blueprints(app)

    return app