Пример #1
1
def init_app(app):
    db.init_app(app)
    cache.init_app(app)
    debug_toolbar.init_app(app)
    app.template_folder = os.path.join(os.path.dirname(__file__), 'templates/')

    migrate = Migrate(app, db)

    # Import and register the different asset bundles
    assets_env = Environment(app)
    assets_env.load_path = [os.path.join(os.path.dirname(__file__), 'static')]
    assets_env.directory = os.path.join(os.path.dirname(__file__), 'static')
    assets_env.url = '/admin/static/'
    # assets_env.register('js_all', js)
    print("directory ", assets_env.directory, os.path.join(os.path.dirname(__file__), 'static/'))
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in list(assets_loader.load_bundles().items()):
        assets_env.register(name, bundle)

    # Setup user handling
    from silverflask.models import User

    user_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(user_adapter)
    user_manager.init_app(app)

    ###
    #  SILVERFLASK
    ###

    upload_path = os.path.join(app.instance_path, app.config["SILVERFLASK_UPLOAD_PATH"])
    app.config["SILVERFLASK_ABSOLUTE_UPLOAD_PATH"] = upload_path
    app.storage_backend = LocalFileStorageBackend(upload_path)


    from silverflask.controllers.page_controller import SiteTreeController
    app.register_blueprint(SiteTreeController.create_blueprint(app))

    from silverflask.core.dev_controller import DevController
    app.register_blueprint(DevController.create_blueprint(app))

    from silverflask.controllers.cms_controller import CMSController, PagesCMSController, FilesCMSController, \
        DataObjectCMSController

    app.register_blueprint(CMSController.create_blueprint(app))
    app.register_blueprint(DataObjectCMSController.create_blueprint(app))
    app.register_blueprint(PagesCMSController.create_blueprint(app))
    app.register_blueprint(FilesCMSController.create_blueprint(app))
    from silverflask.controllers.security_controller import SecurityController
    app.register_blueprint(SecurityController.create_blueprint(app))


    from silverflask.core.theme import init_themes
    init_themes(app)

    from silverflask.controllers.main import setup_processors, init_blueprint
    from silverflask.controllers.cms import bp as cms_bp

    setup_processors(app)
    main = init_blueprint(app)
    app.register_blueprint(main)
    app.register_blueprint(cms_bp, url_prefix='/admin')


    # for rule in app.url_map.iter_rules():
    #     print(rule)

    return app
Пример #2
0
def init_app(app):
    assets = Environment(app)
    assets.debug = app.config.get('DEBUG', False)
    assets.directory = app.static_folder
    assets.url = app.static_url_path
    assets.directory = app.static_folder
    assets.append_path(assets_directory)
    assets.append_path(app.static_folder)
Пример #3
0
def init_app(app):
    assets = Environment(app)
    assets.debug = app.config.get('DEBUG', False)
    assets.directory = app.static_folder
    assets.url = app.static_url_path
    assets.directory = app.static_folder
    assets.append_path(assets_directory)
    assets.append_path(app.static_folder)
    assets.register("h5bp_css", h5bp_css)
    assets.register("h5bp_shiv", h5bp_shiv)
    assets.register("h5bp_head_js", h5bp_head_js)
    if assets.debug:
        assets.register("h5bp_body_js", h5bp_body_js_devel)
    else:
        assets.register("h5bp_body_js", h5bp_body_js_production)
Пример #4
0
def register_web_ui(mgr):
    global manager, assets
    manager = mgr

    assets_cache = os.path.join(manager.config_base, '.webassets-cache')

    if not os.path.isdir(assets_cache):
        os.mkdir(assets_cache)

    assets = Environment(webui_app)
    assets.directory = assets_cache

    for p in _get_plugin_paths():
        assets.append_path(p, url="%s/plugin" % webui_app.url_path)

    assets.cache = assets_cache
    assets.url = '%s/cache' % webui_app.url_path
    if 'debug' in manager.args:
        assets.debug = True

    load_assets()
    load_ui_plugins()

    register_app(webui_app.url_path, webui_app)
    register_home('%s/' % webui_app.url_path)
Пример #5
0
def register_web_ui(mgr):
    global manager, assets
    manager = mgr

    assets_cache = os.path.join(manager.config_base, '.webassets-cache')

    if not os.path.isdir(assets_cache):
        os.mkdir(assets_cache)

    assets = Environment(webui_app)
    assets.directory = assets_cache

    for p in _get_plugin_paths():
        assets.append_path(p, url="%s/plugin" % webui_app.url_path)

    assets.cache = assets_cache
    assets.url = '%s/cache' % webui_app.url_path
    if 'debug' in manager.args:
        assets.debug = True

    load_assets()
    load_ui_plugins()

    register_app(webui_app.url_path, webui_app)
    register_home('%s/' % webui_app.url_path)
Пример #6
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)
Пример #7
0
def configure_static_assets(app):

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

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

  app.environment = assets
Пример #8
0
def setup_app(app):
    """Initialize Assets extension."""
    app.config.setdefault("LESS_RUN_IN_DEBUG", False)
    assets = Environment(app)
    assets.url = app.static_url_path + "/"
    assets.directory = app.static_folder

    commands = (("LESS_BIN", "lessc"),
                ("CLEANCSS_BIN", "cleancss"))
    import subprocess
    for key, cmd in commands:
        try:
            command = app.config.get(key, cmd)
            subprocess.call([command, "--version"],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
        except OSError:
            app.logger.error("Executable `{0}` was not found. You can specify "
                             "it via {1}."
                             .format(cmd, key))
            app.config["ASSETS_DEBUG"] = True
            assets.debug = True

    def _jinja2_new_bundle(tag, collection, name=None, filters=None):
        if len(collection):
            name = "invenio" if name is None else name
            sig = hash(",".join(collection) + "|" + str(filters))
            kwargs = {
                "output": "{0}/{1}-{2}.{0}".format(tag, name, sig),
                "filters": filters,
                "extra": {"rel": "stylesheet"}
            }

            # If LESS_RUN_IN_DEBUG is set to False, then the filters are
            # removed and each less file will be parsed by the less JavaScript
            # library.
            if assets.debug and not app.config.get("LESS_RUN_IN_DEBUG", True):
                kwargs["extra"]["rel"] = "stylesheet/less"
                kwargs["filters"] = None

            return Bundle(*collection, **kwargs)

    app.jinja_env.extend(new_bundle=_jinja2_new_bundle,
                         default_bundle_name='90-invenio')
    app.jinja_env.add_extension(CollectionExtension)

    return app
Пример #9
0
def init_app(app):
    here, f = os.path.split(os.path.abspath(__file__))

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

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

    # load asset bundles
    bundles = YAMLLoader("%s/src/assets.yaml" % here).load_bundles()
    [assets.register(name, bundle) for name, bundle in bundles.iteritems()]
Пример #10
0
def init_app(app):

    # Initialize webassets, the asset pipeline
    assets = Environment(app)
    assets.debug = app.config['DEBUG']

    cur_path = os.path.dirname(os.path.abspath(__file__))
    assets_load_path = os.path.join(cur_path, 'static')

    if ('WEBASSETS_PATH' in app.config):
        assets_load_path = app.config['WEBASSETS_PATH']
        logger.debug('Using asset directory specified in config.')

    logger.debug('Using asset directory of: {0}.'.format(assets_load_path))

    # Output path for compiled assets
    assets.directory = os.path.join(cur_path, 'static')
    assets.url = '/static/'
    assets.from_yaml(os.path.join(cur_path, 'assets.yml'))
    assets.config['closure_compressor_optimization'] = 'SIMPLE_OPTIMIZATIONS'
    assets.config['closure_extra_args'] = ['--language_in', 'ECMASCRIPT5']
    assets.append_path(assets_load_path)

    return assets
Пример #11
0
    page, proxy, result, statistics_memory, statistics_request,
)
from modules.log import initialize

initialize()

application = Flask(
    __name__, static_folder=join(abspath(dirname(__file__)), 'resources'),
)

application.config.from_pyfile('settings.py')

assets = Environment(application)
assets.cache = not application.config['DEBUG']
assets.debug = application.config['DEBUG']
assets.directory = application.static_folder
assets.manifest = 'json:assets/versions.json'
assets.url = application.static_url_path
assets.url_expire = True
assets.versions = 'hash'
assets.register('javascripts', Bundle(
    'vendor/jquery/dist/jquery.js',
    'vendor/angular/angular.min.js',
    'vendor/bootstrap/dist/js/bootstrap.js',
    'vendor/highcharts/highcharts-all.js',
    'javascripts/all.js',
    filters='rjsmin' if not application.config['DEBUG'] else None,
    output='assets/compressed.js',
))
assets.register('stylesheets', Bundle(
    Bundle(
Пример #12
0
            "parameters":
            "-acodec aac -strict experimental -s 1280x720 -aspect = 1280:720 -preset slow -crf 22 -f matroska -vcodec libx265",
            "delete_old_file": False,
            "rename_enabled": False,
            "rename_search": "",
            "rename_replace": ""
        }
    })

app.config["CSRF_SESSION_KEY"] = config["general"]["csrf_session_key"]
app.config["SECRET_KEY"] = config["general"]["secret_key"]

assets = Environment(app)

# use app/static/compiled as output path for webassets' assets
assets.directory = os.path.abspath(app.root_path + os.sep + "static" + os.sep +
                                   "compiled")
assets.url = "/static/compiled"

# use app/static as load path for assets
assets.append_path(app.root_path + os.sep + "static", "static")

# load asset definitions from "static/webassets.py"
assets_loader = PythonAssetsLoader(webassets)
bundles = assets_loader.load_bundles()
for bundle in bundles:
    assets.register(bundle, bundles[bundle])

db = SQLAlchemy(app)
babel = Babel(app)
Compress(app)
Пример #13
0
#!/usr/bin/env python
import os
import random
from flask import Flask, request, session, url_for, redirect, abort, render_template, jsonify, Response, Blueprint
from flask.ext.assets import Environment, Bundle
from webassets.filter import get_filter

SRC_DIR = os.path.abspath(os.path.dirname(__file__))
REPO_DIR = os.path.abspath(os.path.dirname(SRC_DIR))

app = Flask(__name__)
app.secret_key = "f3oiewfophewrihu9ipfoinjfdewmkdcfewrhjgf79834hyf98ewnjmcw"

assets = Environment(app)
assets.url = app.static_url_path
assets.directory = os.path.join(app.static_folder)

pyscss = get_filter('pyscss')
pyscss.load_paths = [
    os.path.join(SRC_DIR, 'static', *('vendor/bootstrap-sass-3.3.6/assets/stylesheets'.split("/"))),
]

scss = Bundle('scss/style.scss', filters=(pyscss,), output='css/style.css')
assets.register('scss_style', scss)

#blueprint = Blueprint('dist', __name__, static_url_path='/dist', static_folder=os.path.join(REPO_DIR, 'dist'))
#app.register_blueprint(blueprint)


@app.route('/')
def index():
Пример #14
0
from sanskrit import Context, analyze, query
import sqlalchemy

app = Flask(__name__)
app.config.from_object('development.config')
try:
    app.config.from_object('server.config')
except ImportError:
    pass


# Assets
# ------
assets = Environment(app)
assets.url = '/static'
assets.directory = app.config['STATIC_DEST']

less_files = ['css/%s.less' % x
              for x in 'base'.split()]
less = Bundle(*less_files, filters='less', output='gen/style.css', debug=False)
assets.register('all-css', less)

js = Bundle(
            # Plugins
            'js/jquery-plugins.js',
            'js/jquery.cookie.js',
            'js/tooltips.js',
            'js/sanscript.js',
            'js/d3-modules.js',
            # Base
            'js/models.js',
Пример #15
0
from dexter.app import app

# setup assets
from flask.ext.assets import Environment, Bundle
assets = Environment(app)
assets.url_expire = False
assets.debug      = app.config['ENV'] == 'development'
assets.directory  = '%s/public' % app.config.root_path
assets.load_path  = ['assets']
assets.url        = '/public'

assets.register('css',
    Bundle(
      'css/bootstrap-3.2.0.min.css',
      'css/bootstrap-theme-3.2.0.min.css',
      'css/font-awesome-4.3.0.min.css',
      'css/datepicker3.css',
      'css/bootstrap-datetimepicker.min.css',
      'css/daterangepicker-bs3.css',
      'css/select2-3.4.8.css',
      'css/select2-bootstrap-3.4.8.css',
      'css/dropzone-3.10.2.css',
      Bundle(
        'css/*.scss',
        filters='pyscss',
        output='css/app.%(version)s.css'),
      output='css/all.%(version)s.css'))

assets.register('mine-css',
    Bundle(
      'css/bootstrap-3.2.0.min.css',
Пример #16
0
import importlib

from flask import Flask, Blueprint
from flask.ext.assets import Bundle, Environment
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask.ext.sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config.from_object('config.development')


# Assets
assets = Environment(app)
assets.url = '/static'
assets.directory = app.config['ASSETS_DEST']

less = Bundle('less/base.less', filters='less', output='gen/style.css')
assets.register('all-css', less)


# Database
db = SQLAlchemy(app)


# Admin
import admin


# Security
from starter.auth.models import User, Role
Пример #17
0
from __future__ import division, print_function, absolute_import, unicode_literals
from flask import Flask
from flask_wtf.csrf import CsrfProtect
from flask.ext.assets import Environment, Bundle
from flask.ext.mail import Mail
from celery import Celery
from webassets.filter import get_filter
from .util import root, config, DictAssetLoader

#: Flask application instance
app = Flask('zg', **config('app'))
app.config.update(config('flask'))

#: Celery instance
celery = Celery('zg-celery')
celery.conf.update(config('celery'))

#: Flask mail instance
mail = Mail()

CsrfProtect(app)

assets = Environment(app)
assets.url = ''
assets.directory = root('./public')
assets.load_path = [app.static_folder, root('./bower_components')]
assets.register(DictAssetLoader(config('assets')).load_bundles(assets))

import zg.routes

def create_invenio_flask_app(**kwargs_config):
    """
    Prepare WSGI Invenio application based on Flask.

    Invenio consists of a new Flask application with legacy support for
    the old WSGI legacy application and the old Python legacy
    scripts (URLs to *.py files).

    An incoming request is processed in the following manner:

     * The Flask application first routes request via its URL routing
       system (see LegacyAppMiddleware.__call__()).

     * One route in the Flask system, will match Python legacy
       scripts (see static_handler_with_legacy_publisher()).

     * If the Flask application aborts the request with a 404 error, the request
       is passed on to the WSGI legacy application (see page_not_found()). E.g.
       either the Flask application did not find a route, or a view aborted the
       request with a 404 error.
    """
    def decorate_build(f):
        @wraps(f)
        def decorator(*args, **kwargs):
            scheme_url = {
                'http': current_app.config['CFG_SITE_URL'],
                'https': current_app.config['CFG_SITE_SECURE_URL']
            }
            force_external = kwargs.get('force_external', True)
            url_scheme = getattr(f.im_self, 'url_scheme', 'http')
            kwargs['force_external'] = False
            url = f(*args, **kwargs)
            if force_external:
                url = scheme_url.get(url_scheme) + url
            return url

        return decorator

    class InvenioFlask(Flask):
        def create_url_adapter(self, request):
            url_adapter = super(InvenioFlask, self).create_url_adapter(request)
            if url_adapter is not None and hasattr(url_adapter, 'build'):
                url_adapter.build = decorate_build(url_adapter.build)
            return url_adapter

    ## The Flask application instance
    _app = InvenioFlask(
        __name__,
        ## Static files are usually handled directly by the webserver (e.g. Apache)
        ## However in case WSGI is required to handle static files too (such
        ## as when running simple server), then this flag can be
        ## turned on (it is done automatically by wsgi_handler_test).
        ## We assume anything under '/' which is static to be server directly
        ## by the webserver from CFG_WEBDIR. In order to generate independent
        ## url for static files use func:`url_for('static', filename='test')`.
        static_url_path='',
        static_folder=CFG_WEBDIR)

    ## Update application config from parameters.
    _app.config.update(kwargs_config)

    if 'SQLALCHEMY_DATABASE_URI' not in _app.config:
        from sqlalchemy.engine.url import URL
        # Global variables
        from invenio.dbquery import CFG_DATABASE_HOST, CFG_DATABASE_PORT,\
            CFG_DATABASE_NAME, CFG_DATABASE_USER, CFG_DATABASE_PASS, \
            CFG_DATABASE_TYPE

        _app.config['SQLALCHEMY_DATABASE_URI'] = URL(
            CFG_DATABASE_TYPE,
            username=CFG_DATABASE_USER,
            password=CFG_DATABASE_PASS,
            host=CFG_DATABASE_HOST,
            database=CFG_DATABASE_NAME,
            port=CFG_DATABASE_PORT,
        )

    ## Let's initialize database.
    from invenio.sqlalchemyutils import db
    db.init_app(_app)

    ## First check that you have all rights to logs
    from invenio.bibtask import check_running_process_user
    check_running_process_user()

    from invenio.pluginutils import PluginContainer
    from invenio.session_flask import InvenioSessionInterface
    from invenio.webuser_flask import InvenioLoginManager, current_user, UserInfo
    from invenio.messages import wash_language, gettext_set_language, \
                                 language_list_long, is_language_rtl
    from invenio.urlutils import create_url, get_canonical_and_alternates_urls
    from invenio.cache import cache
    from invenio.jinja2utils import CollectionExtension, \
                                    LangExtension, hack_jinja2_utf8decoding, \
                                    extend_application_template_filters
    from flask.ext.assets import Environment, Bundle
    from invenio.webinterface_handler_flask_utils import unicodifier, InvenioRequest
    from flaskext.gravatar import Gravatar
    from werkzeug.wrappers import BaseResponse
    from werkzeug.exceptions import HTTPException
    from invenio.flask_sslify import SSLify
    from invenio.webinterface_handler_wsgi import application as legacy_application
    from invenio.webinterface_handler_wsgi import is_mp_legacy_publisher_path, \
                                                  mp_legacy_publisher

    # See note on Jinja2 string decoding using ASCII codec instead of UTF8 in
    # function documentation
    hack_jinja2_utf8decoding()

    # Handle both url with and without trailing slashe by Flask.
    # @blueprint.route('/test')
    # @blueprint.route('/test/') -> not necessary when strict_slashes == False
    _app.url_map.strict_slashes = False

    # SECRET_KEY is needed by Flask Debug Toolbar
    SECRET_KEY = _app.config.get('SECRET_KEY') or CFG_SITE_SECRET_KEY
    if not SECRET_KEY or SECRET_KEY == '':
        fill_secret_key = """
    Set variable CFG_SITE_SECRET_KEY with random string in invenio-local.conf.

    You can use following commands:
    $ %s
    $ %s
        """ % (CFG_BINDIR + os.sep + 'inveniocfg --create-secret-key',
               CFG_BINDIR + os.sep + 'inveniocfg --update-config-py')
        try:
            raise Exception(fill_secret_key)
        except Exception:
            register_exception(alert_admin=True,
                               subject="Missing CFG_SITE_SECRET_KEY")
            raise Exception(fill_secret_key)

    _app.config["SECRET_KEY"] = SECRET_KEY

    # Enable Flask Debug Toolbar early to also catch HTTPS redirects
    if 'debug-toolbar' in getattr(config, 'CFG_DEVEL_TOOLS', []):
        _app.config["DEBUG_TB_ENABLED"] = True
        _app.config[
            "DEBUG_TB_INTERCEPT_REDIRECTS"] = 'intercept-redirects' in getattr(
                config, 'CFG_DEVEL_TOOLS', [])
        from flask_debugtoolbar import DebugToolbarExtension

        class InvenioDebugToolbarExtension(DebugToolbarExtension):
            def _show_toolbar(self):
                user_info = UserInfo(session.get('user_id'))
                # Enable debug toolbar only for super admin.
                if not user_info.is_super_admin:
                    return False
                return super(InvenioDebugToolbarExtension,
                             self)._show_toolbar()

        InvenioDebugToolbarExtension(_app)

    # Set email backend for Flask-Email plugin
    from invenio.mailutils import initialize_email_backend
    initialize_email_backend(_app)

    if CFG_HAS_HTTPS_SUPPORT:
        # Makes request always run over HTTPS.
        _sslify = SSLify(_app)

        if not CFG_FULL_HTTPS:

            @_sslify.criteria_handler
            def criteria():
                """Extends criteria when to stay on HTTP site."""
                _force_https = False
                if request.blueprint in current_app.blueprints:
                    _force_https = current_app.blueprints[request.blueprint].\
                                   _force_https

                view_func = current_app.view_functions.get(request.endpoint)
                if view_func is not None and hasattr(view_func,
                                                     '_force_https'):
                    _force_https = view_func._force_https

                return not (_force_https or session.need_https())

    class LegacyAppMiddleware(object):
        def __init__(self, app):
            self.app = app

        def __call__(self, environ, start_response):
            if remote_debugger:
                remote_debugger.start()

            with self.app.request_context(environ):
                g.start_response = start_response
                try:
                    response = self.app.full_dispatch_request()
                except Exception as e:
                    register_exception(req=request, alert_admin=True)
                    response = self.app.handle_exception(e)

                return response(environ, start_response)

    _app.wsgi_app = LegacyAppMiddleware(_app)

    @_app.errorhandler(404)
    def page_not_found(error):
        try:
            response = legacy_application(request.environ, g.start_response)
            if not isinstance(response, BaseResponse):
                response = current_app.make_response(str(response))
            return response
        except HTTPException:
            return render_template("404.html"), 404

    @_app.errorhandler(401)
    def do_login_first(error=401):
        """Displays login page when user is not authorised."""
        if request.is_xhr:
            return _("Authorization failure"), 401
        flash(_("Authorization failure"), 'error')
        from invenio.webaccount_blueprint import login
        return login(referer=request.url), 401

    @_app.endpoint('static')
    @_app.route(_app.static_url_path + '/<path:filename>',
                methods=['POST', 'PUT'])
    def static_handler_with_legacy_publisher(*args, **kwargs):
        """
        Adds support for legacy publisher.

        NOTE: It changes order of url page lookup. First, the invenio_handler
        will be called and on 404 error the mp_legacy_publisher is called.
        """
        possible_module, possible_handler = is_mp_legacy_publisher_path(
            request.environ['PATH_INFO'])
        if possible_module is not None:
            legacy_publisher = lambda req: \
                mp_legacy_publisher(req, possible_module, possible_handler)
            return legacy_application(request.environ,
                                      g.start_response,
                                      handler=legacy_publisher)

        # Static file serving for devserver
        # ---------------------------------
        # Apache normally serve all static files, but if we are using the
        # devserver we need to serve static files here. Werkzeugs default
        # behaviour is to return a '405 Method not allowed' for POST requests
        # to static files. However, if we abort all POST requests with 405, the
        # legacy_application (see page_not_found()) will not be given a chance
        # to serve static files as it only get's invokved when we abort with a
        # 404. Hence, on POST requests, we first check if the static file exists,
        # and if it does we return we abort the request with a 405.
        if not CFG_FLASK_SERVE_STATIC_FILES:
            abort(404)
        else:
            static_file_response = _app.send_static_file(*args, **kwargs)
            if request.method in ['POST', 'PUT']:
                abort(405)
            else:
                return static_file_response

    if CFG_FLASK_CACHE_TYPE not in [None, 'null']:
        _app.jinja_options = dict(_app.jinja_options,
                                  auto_reload=False,
                                  cache_size=-1,
                                  bytecode_cache=MemcachedBytecodeCache(
                                      cache, prefix="jinja::", timeout=3600))

    ## Let's customize the template loader to first look into
    ## /opt/invenio/etc-local/templates and then into
    ## /opt/invenio/etc/templates
    _app.jinja_loader = FileSystemLoader([
        join(CFG_ETCDIR + '-local', 'templates'),
        join(CFG_ETCDIR, 'templates')
    ])

    ## Let's attach our session handling (which is bridging with the native
    ## Invenio session handling
    _app.session_interface = InvenioSessionInterface()

    ## Set custom request class
    _app.request_class = InvenioRequest

    ## Let's load the whole invenio.config into Flask :-) ...
    _app.config.from_object(config)

    ## ... and map certain common parameters
    _app.config['SESSION_COOKIE_NAME'] = CFG_WEBSESSION_COOKIE_NAME
    _app.config['PERMANENT_SESSION_LIFETIME'] = \
        CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER * CFG_WEBSESSION_ONE_DAY
    _app.config['USE_X_SENDFILE'] = CFG_BIBDOCFILE_USE_XSENDFILE
    _app.config['DEBUG'] = CFG_DEVEL_SITE > 0
    _app.debug = CFG_DEVEL_SITE > 0
    language_list_long = language_list_long()
    language_labordoc_list = [
        ln for ln in language_list_long if ln[0] in ['en', 'es', 'fr']
    ]
    _app.config['CFG_LANGUAGE_LIST_LONG'] = [
        (lang, longname.decode('utf-8'))
        for (lang, longname) in language_list_long
    ]
    _app.config['CFG_LANGUAGE_LABORDOC_LIST'] = [
        (lang, longname.decode('utf-8'))
        for (lang, longname) in language_labordoc_list
    ]

    ## Invenio is all using str objects. Let's change them to unicode
    _app.config.update(unicodifier(dict(_app.config)))

    ## Cache
    _app.config['CACHE_TYPE'] = CFG_FLASK_CACHE_TYPE
    # FIXME problem in Flask-Cache==0.11.1
    cache.app = _app
    cache.init_app(_app)
    if CFG_FLASK_CACHE_TYPE == 'redis':

        def with_try_except_block(f):
            def decorator(*args, **kwargs):
                try:
                    return f(*args, **kwargs)
                except Exception:
                    register_exception(alert_admin=True)
                    pass

            return decorator

        ## When the redis is down, we would like to keep the site running.
        cache.cache._client.execute_command = with_try_except_block(
            cache.cache._client.execute_command)

    # FIXME problem in Flask-Cache==0.11.1
    cache.app = current_app

    _flask_log_handler = RotatingFileHandler(
        os.path.join(CFG_LOGDIR, 'flask.log'))
    _flask_log_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s '
                  '[in %(pathname)s:%(lineno)d]'))
    _app.logger.addHandler(_flask_log_handler)

    # Let's create login manager.
    _login_manager = InvenioLoginManager(_app)
    _login_manager.login_view = 'webaccount.login'
    _login_manager.anonymous_user = UserInfo
    _login_manager.unauthorized_handler(do_login_first)

    # Let's create main menu.
    class Menu(object):
        def __init__(self,
                     id='',
                     title='',
                     url='',
                     order=None,
                     children=None,
                     display=lambda: True):
            self.id = id
            self.title = title
            self.url = url
            self.children = children or {}
            self.order = order or 100
            self.display = display

    # Let's create assets environment.
    _assets = Environment(_app)
    _assets.debug = 'assets-debug' in getattr(config, 'CFG_DEVEL_TOOLS', [])
    _assets.directory = config.CFG_WEBDIR

    def _jinja2_new_bundle(tag, collection, name=None):
        if not _assets.debug:
            files = [
                f for f in collection
                if os.path.isfile(os.path.join(_assets.directory, f))
            ]
            if len(files) != len(collection):
                ## Turn on debuging to generate 404 request on missing files.
                _assets.debug = True
                current_app.logger.error(
                    'Missing files: ' + ','.join(set(collection) - set(files)))

        if len(collection):
            return Bundle(output="%s/%s-%s.%s" %
                          (tag, 'invenio' if name is None else name,
                           hash('|'.join(collection)), tag),
                          *collection)

    _app.jinja_env.extend(new_bundle=_jinja2_new_bundle,
                          default_bundle_name='90-invenio')

    _app.jinja_env.add_extension(CollectionExtension)
    _app.jinja_env.add_extension(LangExtension)
    _app.jinja_env.add_extension('jinja2.ext.do')

    # Let's extend application with custom template filters.
    extend_application_template_filters(_app)

    # Let's create Gravatar bridge.
    _gravatar = Gravatar(_app,
                         size=100,
                         rating='g',
                         default='retro',
                         force_default=False,
                         force_lower=False)
    del _gravatar

    # Let's set the user language
    from invenio.webinterface_handler_flask_utils import guess_language
    _app.before_request(guess_language)

    # Let's extend application with more custom templete filters
    from invenio.jinja2utils import inject_utils
    _app.context_processor(inject_utils)

    @_login_manager.user_loader
    def _load_user(uid):
        """
        Function should not raise an exception if uid is not valid
        or User was not found in database.
        """
        return UserInfo(int(uid))

    @_app.before_request
    def reset_template_context_processor():
        g._template_context_processor = []

    @_app.context_processor
    def _inject_template_context():
        context = {}
        if not hasattr(g, '_template_context_processor'):
            reset_template_context_processor()
        for func in g._template_context_processor:
            context.update(func())
        return context

    def _invenio_blueprint_plugin_builder(plugin):
        """
        Handy function to bridge pluginutils with (Invenio) blueprints.
        """
        if plugin.__name__ in CFG_FLASK_DISABLED_BLUEPRINTS or \
           plugin.__name__.split('.')[-1] in CFG_FLASK_DISABLED_BLUEPRINTS:
            _app.logger.info(
                '%s is excluded by CFG_FLASK_DISABLED_BLUEPRINTS' %
                plugin_name)
            return
        from invenio.webinterface_handler_flask_utils import InvenioBlueprint
        if 'blueprint' in dir(plugin):
            candidate = getattr(plugin, 'blueprint')
            if isinstance(candidate, InvenioBlueprint):
                return candidate
        _app.logger.error('%s is not a valid blueprint plugin' % plugin_name)

    ## Let's load all the blueprints that are composing this Invenio instance
    _BLUEPRINTS = [
        m for m in map(
            _invenio_blueprint_plugin_builder,
            autodiscover_modules(['invenio'],
                                 related_name_re='.+_blueprint.py',
                                 ignore_exceptions=True)) if m is not None
    ]

    _app.config['breadcrumbs_map'] = {}
    _app.config['menubuilder_map'] = {}

    ## Let's attach all the blueprints
    from invenio.webinterface_handler_flask_utils import _
    for plugin in _BLUEPRINTS:
        _app.register_blueprint(plugin)
        if plugin.config:
            ## Let's include the configuration parameters of the config file.
            ## E.g. if the blueprint specify the config string
            ## 'invenio.webmessage_config' any uppercase variable defined in
            ## the module invenio.webmessage_config is loaded into the system.
            _app.config.from_object(plugin.config)
        if plugin.breadcrumbs:
            _app.config['breadcrumbs_map'][plugin.name] = plugin.breadcrumbs
        _app.config['breadcrumbs_map'].update(plugin.breadcrumbs_map)

        ## Let's build global menu. Each blueprint can plug its own menu items.
        if plugin.menubuilder:
            _app.config['menubuilder_map'].update(
                (m[0], Menu(*m)) for m in plugin.menubuilder)
        _app.config['menubuilder_map'].update(plugin.menubuilder_map)

    _app.config['menubuilder_map'].update({
        'main.admin':
        Menu('main.admin', _('Administration'), 'help.admin', 9998, [],
             lambda: current_user.is_admin if current_user else False),
        'main.help':
        Menu('main.help', _('Help'), 'help', 9999)
    })

    menu = {
        'main': Menu('main', '', ''),
        'personalize': Menu('personalize', '', '')
    }
    for key, item in _app.config['menubuilder_map'].iteritems():
        start = menu

        if '.' not in key:
            if key in menu:
                menu[key] = item.children.update(menu[key].children)
            else:
                menu[key] = item
            continue

        keys = key.split('.')
        for k in keys[:-1]:
            try:
                start = start[k].children
            except:
                start[k] = Menu()
                start = start[k].children

        if keys[-1] in start:
            item.children.update(start[keys[-1]].children)
        start[keys[-1]] = item

    _app.config['menubuilder_map'] = menu

    # Flask-Admin
    from invenio.adminutils import register_admin
    register_admin(_app)

    try:
        ## When deploying Invenio, one can prepare a module called
        ## webinterface_handler_local.py to be deployed under
        ## CFG_PYLIBDIR/invenio directory, and containing a function called
        ## customize_app which should accept a Flask application.
        ## This function has a chance to modify the application as needed
        ## including changing the URL routing map.
        # pylint: disable=E0611
        from invenio.webinterface_handler_local import customize_app
        # pylint: enable=E0611
        customize_app(_app)
    except ImportError:
        ## No customization needed.
        pass

    return _app
Пример #19
0
        "encoding": {
            "parameters": "-acodec aac -strict experimental -s 1280x720 -aspect = 1280:720 -preset slow -crf 22 -f matroska -vcodec libx265",
            "delete_old_file": False,
            "rename_enabled": False,
            "rename_search": "",
            "rename_replace": ""
        }
    })

app.config["CSRF_SESSION_KEY"] = config["general"]["csrf_session_key"]
app.config["SECRET_KEY"] = config["general"]["secret_key"]

assets = Environment(app)

# use app/static/compiled as output path for webassets' assets
assets.directory = os.path.abspath(app.root_path + os.sep + "static" + os.sep + "compiled")
assets.url = "/static/compiled"

# use app/static as load path for assets
assets.append_path(app.root_path + os.sep + "static", "static")

# load asset definitions from "static/webassets.py"
assets_loader = PythonAssetsLoader(webassets)
bundles = assets_loader.load_bundles()
for bundle in bundles:
    assets.register(bundle, bundles[bundle])

db = SQLAlchemy(app)
babel = Babel(app)
Compress(app)
Пример #20
0
import logging
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)

loggers = [app.logger, logging.getLogger('elasticsearch')]
for logger in loggers:
    logger.setLevel(logging.WARNING)
    logger.addHandler(stream_handler)



# When I'm ready to fix this with bower and stuff
# look at http://adambard.com/blog/fresh-flask-setup/

assets = Environment(app)
assets.directory = 'eheritage/static/'
assets.url = '/static/'
assets.debug = True

js = Bundle('app.js',
    filters='jsmin', output='gen/packed.js')
assets.register('js_all', js)

# scss = Bundle('*.scss', filters='scss', output='gen/scss.css')
# css = Bundle('style.css', # scss,
#     filters='pyscss,cssmin', output='gen/style.css')

# assets.register('css_all', css)


app.json_encoder = IterableAwareEncoder
Пример #21
0
def init_app(app):
    db.init_app(app)
    cache.init_app(app)
    debug_toolbar.init_app(app)
    app.template_folder = os.path.join(os.path.dirname(__file__), 'templates/')

    migrate = Migrate(app, db)

    # Import and register the different asset bundles
    assets_env = Environment(app)
    assets_env.load_path = [os.path.join(os.path.dirname(__file__), 'static')]
    assets_env.directory = os.path.join(os.path.dirname(__file__), 'static')
    assets_env.url = '/admin/static/'
    # assets_env.register('js_all', js)
    print("directory ", assets_env.directory,
          os.path.join(os.path.dirname(__file__), 'static/'))
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in list(assets_loader.load_bundles().items()):
        assets_env.register(name, bundle)

    # Setup user handling
    from silverflask.models import User

    user_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(user_adapter)
    user_manager.init_app(app)

    ###
    #  SILVERFLASK
    ###

    upload_path = os.path.join(app.instance_path,
                               app.config["SILVERFLASK_UPLOAD_PATH"])
    app.config["SILVERFLASK_ABSOLUTE_UPLOAD_PATH"] = upload_path
    app.storage_backend = LocalFileStorageBackend(upload_path)

    from silverflask.controllers.page_controller import SiteTreeController
    app.register_blueprint(SiteTreeController.create_blueprint(app))

    from silverflask.core.dev_controller import DevController
    app.register_blueprint(DevController.create_blueprint(app))

    from silverflask.controllers.cms_controller import CMSController, PagesCMSController, FilesCMSController, \
        DataObjectCMSController

    app.register_blueprint(CMSController.create_blueprint(app))
    app.register_blueprint(DataObjectCMSController.create_blueprint(app))
    app.register_blueprint(PagesCMSController.create_blueprint(app))
    app.register_blueprint(FilesCMSController.create_blueprint(app))
    from silverflask.controllers.security_controller import SecurityController
    app.register_blueprint(SecurityController.create_blueprint(app))

    from silverflask.core.theme import init_themes
    init_themes(app)

    from silverflask.controllers.main import setup_processors, init_blueprint
    from silverflask.controllers.cms import bp as cms_bp

    setup_processors(app)
    main = init_blueprint(app)
    app.register_blueprint(main)
    app.register_blueprint(cms_bp, url_prefix='/admin')

    # for rule in app.url_map.iter_rules():
    #     print(rule)

    return app
Пример #22
0
from dexter.app import app

# setup assets
from flask.ext.assets import Environment, Bundle
assets = Environment(app)
assets.url_expire = False
assets.debug = app.config['ENV'] == 'development'
assets.directory = '%s/public' % app.config.root_path
assets.load_path = ['assets']
assets.url = '/public'

assets.register(
    'css',
    Bundle('css/bootstrap-3.2.0.min.css',
           'css/bootstrap-theme-3.2.0.min.css',
           'css/font-awesome-4.3.0.min.css',
           'css/datepicker3.css',
           'css/bootstrap-datetimepicker.min.css',
           'css/daterangepicker-bs3.css',
           'css/select2-3.4.8.css',
           'css/select2-bootstrap-3.4.8.css',
           'css/dropzone-3.10.2.css',
           Bundle('css/*.scss',
                  filters='pyscss',
                  output='css/app.%(version)s.css'),
           output='css/all.%(version)s.css'))

assets.register(
    'mine-css',
    Bundle('css/bootstrap-3.2.0.min.css',
           'css/bootstrap-theme-3.2.0.min.css',
Пример #23
0
application = Flask(__name__,
                    static_folder=join(abspath(dirname(__file__)),
                                       'resources'))

application.config.from_pyfile('settings/__init__.py')
application.config.from_pyfile(
    'settings/%(environment)s.py' % {
        'environment': environ.get('environment', 'serve'),
    },
    silent=True)

assets = Environment(application)
assets.cache = False
assets.debug = application.config['DEBUG']
assets.directory = application.static_folder
assets.manifest = 'json:assets/versions.json'
assets.url = application.static_url_path
assets.url_expire = True
assets.versions = 'hash'
assets.register(
    'javascripts',
    Bundle(
        'vendor/jquery/dist/jquery.js',
        'vendor/bootstrap/dist/js/bootstrap.js',
        filters='rjsmin' if not application.config['DEBUG'] else None,
        output='assets/compressed.js',
    ))
assets.register(
    'stylesheets',
    Bundle(