Example #1
0
def connect_signals(app):
    appcontext_popped.connect(handle_appcontext_popped)
    appcontext_pushed.connect(handle_appcontext_pushed)
    appcontext_tearing_down.connect(handle_appcontext_tearing_down)

    before_render_template.connect(handle_before_render_template, app)
    got_request_exception.connect(handle_got_request_exception, app)

    request_finished.connect(handle_request_finished, app)
    request_started.connect(handle_request_started, sender=app, weak=True)
    request_tearing_down.connect(handle_request_tearing_down, app, False)

    template_rendered.connect(handle_template_rendered, sender=app)
Example #2
0
def create_app(config_file):
    app = Flask(__name__)

    app.glados_config = read_config(config_file)
    if app.glados_config.config.ngrok.enabled:
        logging.debug("launching ngrok")
        # app.ngrok = setup_ngrok(app)
        register_views(app)
        setup_ngrok(app)
        appcontext_pushed.connect(setup_ngrok, app)
        appcontext_tearing_down.connect(teardown_ngrok, app)

    return app
Example #3
0
    def _context_callbacks(app, key, original_context=_CONTEXT_MISSING):
        """Register the callbacks we need to properly pop and push the
        app-local context for a component.

        Args:
            app (flask.Flask): The app who this context belongs to. This is the
                only sender our Blinker signal will listen to.
            key (str): The key on ``_CONTEXT_LOCALS`` that this app's context
                listens to.

        Kwargs:
            original_context (dict): The original context present whenever
                these callbacks were registered. We will restore the context to
                this value whenever the app context gets popped.

        Returns:
            (function, function): A two-element tuple of the dynamic functions
                we generated as appcontext callbacks. The first element is the
                callback for ``appcontext_pushed`` (i.e., get and store the
                current context) and the second element is the callback for
                ``appcontext_popped`` (i.e., restore the current context to
                to it's original value).
        """
        def _get_context(dummy_app):
            """Set the context proxy so that it points to a specific context.
            """
            _CONTEXT_LOCALS.context = _CONTEXT_LOCALS(key)  # pylint: disable=assigning-non-slot

        def _clear_context(dummy_app):
            """Remove the context proxy that points to a specific context and
            restore the original context, if there was one.
            """
            try:
                del _CONTEXT_LOCALS.context
            except AttributeError:
                pass

            if original_context is not _CONTEXT_MISSING:
                setattr(_CONTEXT_LOCALS, key, original_context)

        # store for later so Blinker doesn't remove these listeners and so we
        # don't add them twice
        _CONTEXT_CALLBACK_MAP[app] = (_get_context, _clear_context)

        # and listen for any app context changes
        appcontext_pushed.connect(_get_context, app)
        appcontext_popped.connect(_clear_context, app)

        return (_get_context, _clear_context)
Example #4
0
    def init_app(self, app):
        Service.init_app(self, app)
        state = app.extensions[self.name]

        whoosh_base = app.config.get("WHOOSH_BASE")
        if not whoosh_base:
            whoosh_base = "whoosh"  # Default value

        if not os.path.isabs(whoosh_base):
            whoosh_base = os.path.join(app.instance_path, whoosh_base)

        state.whoosh_base = os.path.abspath(whoosh_base)

        if not self._listening:
            event.listen(Session, "after_flush", self.after_flush)
            event.listen(Session, "after_commit", self.after_commit)
            self._listening = True

        appcontext_pushed.connect(self.clear_update_queue, app)
        signals.register_js_api.connect(self._do_register_js_api)
Example #5
0
    def init_app(self, app):
        Service.init_app(self, app)
        state = app.extensions[self.name]

        whoosh_base = Path(app.config.get("WHOOSH_BASE", "whoosh"))

        if not whoosh_base.is_absolute():
            whoosh_base = app.instance_path / whoosh_base

        if not whoosh_base.is_dir():
            whoosh_base.mkdir(parents=True)

        state.whoosh_base = text_type(whoosh_base.resolve())

        if not self._listening:
            event.listen(Session, "after_flush", self.after_flush)
            event.listen(Session, "after_commit", self.after_commit)
            self._listening = True

        appcontext_pushed.connect(self.clear_update_queue, app)
        signals.register_js_api.connect(self._do_register_js_api)
Example #6
0
    def init_app(self, app):
        Service.init_app(self, app)
        state = app.extensions[self.name]

        whoosh_base = Path(app.config.get("WHOOSH_BASE", "whoosh"))

        if not whoosh_base.is_absolute():
            whoosh_base = app.instance_path / whoosh_base

        if not whoosh_base.is_dir():
            whoosh_base.mkdir(parents=True)

        state.whoosh_base = str(whoosh_base.resolve())

        if not self._listening:
            event.listen(Session, "after_flush", self.after_flush)
            event.listen(Session, "after_commit", self.after_commit)
            self._listening = True

        appcontext_pushed.connect(self.clear_update_queue, app)
        signals.register_js_api.connect(self._do_register_js_api)
    def start(self):
        """
        Starts the Application
        :return:
        """
        appcontext_tearing_down.connect(self.stop, self.app)
        appcontext_pushed.connect(self.app_pushed, self.app)

        self.fake_module = Thread(target=run_fake_module,
                                  args=(self.startapp, self.runapp))

        self.channels = Channels(self)
        self.channels.register_api()

        self.sensors = Sensors(self)
        # self.sensors.register_api()

        self.modules = Modules(self)
        self.modules.register_api()

        self.website = Website(self)
        self.website.register_url()
Example #8
0
    def __init__(self, name=None, config=None, *args, **kwargs):
        kwargs.setdefault('instance_relative_config', True)
        name = name or __name__

        # used by make_config to determine if we try to load config from instance /
        # environment variable /...
        self._ABILIAN_INIT_TESTING_FLAG = (getattr(config, 'TESTING', False)
                                           if config else False)
        Flask.__init__(self, name, *args, **kwargs)
        del self._ABILIAN_INIT_TESTING_FLAG

        self._setup_script_manager()
        appcontext_pushed.connect(self._install_id_generator)
        ServiceManager.__init__(self)
        PluginManager.__init__(self)
        self.default_view = ViewRegistry()
        self.js_api = dict()

        if config:
            self.config.from_object(config)

        # at this point we have loaded all external config files:
        # SQLALCHEMY_DATABASE_URI is definitively fixed (it cannot be defined in
        # database AFAICT), and LOGGING_FILE cannot be set in DB settings.
        self.setup_logging()

        configured = bool(self.config.get('SQLALCHEMY_DATABASE_URI'))
        self.config['CONFIGURED'] = configured

        if not self.testing:
            self.init_sentry()

        if not configured:
            # set fixed secret_key so that any unconfigured worker will use, so that
            # session can be used during setup even if multiple processes are
            # processing requests.
            self.config['SECRET_KEY'] = 'abilian_setup_key'

        # time to load config bits from database: 'settings'
        # First init required stuff: db to make queries, and settings service
        extensions.db.init_app(self)
        settings_service.init_app(self)

        if configured:
            with self.app_context():
                try:
                    settings = self.services['settings'].namespace(
                        'config').as_dict()
                except sa.exc.DatabaseError as exc:
                    # we may get here if DB is not initialized and "settings" table is
                    # missing. Command "initdb" must be run to initialize db, but first we
                    # must pass app init
                    if not self.testing:
                        # durint tests this message will show up on every test, since db is
                        # always recreated
                        logging.error(exc.message)
                    self.db.session.rollback()
                else:
                    self.config.update(settings)

        if not self.config.get('FAVICO_URL'):
            self.config['FAVICO_URL'] = self.config.get('LOGO_URL')

        languages = self.config.get('BABEL_ACCEPT_LANGUAGES')
        if languages is None:
            languages = abilian.i18n.VALID_LANGUAGES_CODE
        else:
            languages = tuple(lang for lang in languages
                              if lang in abilian.i18n.VALID_LANGUAGES_CODE)
        self.config['BABEL_ACCEPT_LANGUAGES'] = languages

        self._jinja_loaders = list()
        self.register_jinja_loaders(
            jinja2.PackageLoader('abilian.web', 'templates'))

        js_filters = (('closure_js', )
                      if self.config.get('PRODUCTION', False) else None)

        self._assets_bundles = {
            'css': {
                'options':
                dict(filters=('less', 'cssmin'),
                     output='style-%(version)s.min.css')
            },
            'js-top': {
                'options':
                dict(output='top-%(version)s.min.js', filters=js_filters)
            },
            'js': {
                'options':
                dict(output='app-%(version)s.min.js', filters=js_filters)
            },
        }

        # bundles for JS translations
        for lang in languages:
            code = 'js-i18n-' + lang
            filename = 'lang-' + lang + '-%(version)s.min.js'
            self._assets_bundles[code] = {
                'options': dict(output=filename, filters=js_filters),
            }

        for http_error_code in (403, 404, 500):
            self.install_default_handler(http_error_code)

        with self.app_context():
            self.init_extensions()
            self.register_plugins()
            self.add_access_controller('static',
                                       allow_access_for_roles(Anonymous),
                                       endpoint=True)
            # debugtoolbar: this is needed to have it when not authenticated on a
            # private site. We cannot do this in init_debug_toolbar, since auth
            # service is not yet installed
            self.add_access_controller('debugtoolbar',
                                       allow_access_for_roles(Anonymous))
            self.add_access_controller('_debug_toolbar.static',
                                       allow_access_for_roles(Anonymous),
                                       endpoint=True)

        self.maybe_register_setup_wizard()
        self._finalize_assets_setup()
        # At this point all models should have been imported: time to configure
        # mappers. Normally Sqlalchemy does it when needed but mappers may be
        # configured inside sa.orm.class_mapper() which hides a misconfiguration: if
        # a mapper is misconfigured its exception is swallowed by
        # class_mapper(model) results in this laconic (and misleading) message:
        # "model is not mapped"
        sa.orm.configure_mappers()

        signals.components_registered.send(self)
        self.before_first_request(self._set_current_celery_app)
        self.before_first_request(lambda: signals.register_js_api.send(self))

        request_started.connect(self._setup_nav_and_breadcrumbs)

        # Initialize Abilian core services.
        # Must come after all entity classes have been declared.
        # Inherited from ServiceManager. Will need some configuration love later.
        if not self.config.get('TESTING', False):
            with self.app_context():
                self.start_services()
Example #9
0
    def __init__(self, name=None, config=None, *args, **kwargs):
        name = name or __name__

        instance_path = os.environ.get("FLASK_INSTANCE_PATH")
        if instance_path:
            kwargs["instance_path"] = instance_path
        else:
            kwargs.setdefault("instance_relative_config", True)

        # used by make_config to determine if we try to load config from
        # instance / environment variable /...
        self._ABILIAN_INIT_TESTING_FLAG = (getattr(config, "TESTING", False)
                                           if config else False)
        Flask.__init__(self, name, *args, **kwargs)
        del self._ABILIAN_INIT_TESTING_FLAG

        self._setup_script_manager()
        appcontext_pushed.connect(self._install_id_generator)

        ServiceManager.__init__(self)
        PluginManager.__init__(self)
        JinjaManagerMixin.__init__(self)

        self.default_view = ViewRegistry()
        self.js_api = dict()

        self.configure(config)

        # At this point we have loaded all external config files:
        # SQLALCHEMY_DATABASE_URI is definitively fixed (it cannot be defined in
        # database AFAICT), and LOGGING_FILE cannot be set in DB settings.
        self.setup_logging()

        configured = bool(self.config.get("SQLALCHEMY_DATABASE_URI"))
        self.config["CONFIGURED"] = configured

        if not self.testing:
            self.init_sentry()

        if not configured:
            # set fixed secret_key so that any unconfigured worker will use,
            # so that session can be used during setup even if
            # multiple processes are processing requests.
            self.config["SECRET_KEY"] = "abilian_setup_key"

        # time to load config bits from database: 'settings'
        # First init required stuff: db to make queries, and settings service
        extensions.db.init_app(self)
        settings_service.init_app(self)

        if configured:
            with self.app_context():
                try:
                    settings = self.services["settings"]
                    config = settings.namespace("config").as_dict()
                except sa.exc.DatabaseError as exc:
                    # We may get here if DB is not initialized and "settings"
                    # table is missing. Command "initdb" must be run to
                    # initialize db, but first we must pass app init.
                    if not self.testing:
                        # durint tests this message will show up on every test,
                        # since db is always recreated
                        logging.error(exc)
                    db.session.rollback()
                else:
                    self.config.update(config)

        if not self.config.get("FAVICO_URL"):
            self.config["FAVICO_URL"] = self.config.get("LOGO_URL")

        self.register_jinja_loaders(jinja2.PackageLoader("abilian.web"))

        self.init_assets()
        self.install_default_handlers()

        with self.app_context():
            self.init_extensions()
            self.register_plugins()
            self.add_access_controller("static",
                                       allow_access_for_roles(Anonymous),
                                       endpoint=True)
            # debugtoolbar: this is needed to have it when not authenticated
            # on a private site. We cannot do this in init_debug_toolbar,
            # since auth service is not yet installed.
            self.add_access_controller("debugtoolbar",
                                       allow_access_for_roles(Anonymous))
            self.add_access_controller(
                "_debug_toolbar.static",
                allow_access_for_roles(Anonymous),
                endpoint=True,
            )

        self.maybe_register_setup_wizard()
        self._finalize_assets_setup()

        # At this point all models should have been imported: time to configure
        # mappers. Normally Sqlalchemy does it when needed but mappers may be
        # configured inside sa.orm.class_mapper() which hides a
        # misconfiguration: if a mapper is misconfigured its exception is
        # swallowed by class_mapper(model) results in this laconic
        # (and misleading) message: "model is not mapped"
        sa.orm.configure_mappers()

        signals.components_registered.send(self)
        self.before_first_request(self._set_current_celery_app)
        self.before_first_request(lambda: signals.register_js_api.send(self))

        request_started.connect(self._setup_nav_and_breadcrumbs)

        # Initialize Abilian core services.
        # Must come after all entity classes have been declared.
        # Inherited from ServiceManager. Will need some configuration love
        # later.
        if not self.config.get("TESTING", False):
            with self.app_context():
                self.start_services()

        if os.environ.get("FLASK_VALIDATE_HTML"):
            # Workaround circular import
            from abilian.testing.validation import validate_response

            self.after_request(validate_response)
Example #10
0
  def __init__(self, name=None, config=None, *args, **kwargs):
    kwargs.setdefault('instance_relative_config', True)
    name = name or __name__

    # used by make_config to determine if we try to load config from instance /
    # environment variable /...
    self._ABILIAN_INIT_TESTING_FLAG = (getattr(config, 'TESTING', False)
                                       if config else False)
    Flask.__init__(self, name, *args, **kwargs)
    del self._ABILIAN_INIT_TESTING_FLAG

    self._setup_script_manager()
    appcontext_pushed.connect(self._install_id_generator)
    ServiceManager.__init__(self)
    PluginManager.__init__(self)
    self.default_view = ViewRegistry()
    self.js_api = dict()

    if config:
      self.config.from_object(config)

    # at this point we have loaded all external config files:
    # SQLALCHEMY_DATABASE_URI is definitively fixed (it cannot be defined in
    # database AFAICT), and LOGGING_FILE cannot be set in DB settings.
    self.setup_logging()

    configured = bool(self.config.get('SQLALCHEMY_DATABASE_URI'))
    self.config['CONFIGURED'] = configured

    if not self.testing:
      self.init_sentry()

    if not configured:
      # set fixed secret_key so that any unconfigured worker will use, so that
      # session can be used during setup even if multiple processes are
      # processing requests.
      self.config['SECRET_KEY'] = 'abilian_setup_key'

    # time to load config bits from database: 'settings'
    # First init required stuff: db to make queries, and settings service
    extensions.db.init_app(self)
    settings_service.init_app(self)

    if configured:
      with self.app_context():
        try:
          settings = self.services['settings'].namespace('config').as_dict()
        except sa.exc.DatabaseError as exc:
          # we may get here if DB is not initialized and "settings" table is
          # missing. Command "initdb" must be run to initialize db, but first we
          # must pass app init
          if not self.testing:
            # durint tests this message will show up on every test, since db is
            # always recreated
            logging.error(exc.message)
          self.db.session.rollback()
        else:
          self.config.update(settings)

    if not self.config.get('FAVICO_URL'):
      self.config['FAVICO_URL'] = self.config.get('LOGO_URL')

    languages = self.config.get('BABEL_ACCEPT_LANGUAGES')
    if languages is None:
      languages = abilian.i18n.VALID_LANGUAGES_CODE
    else:
      languages = tuple(lang for lang in languages
                        if lang in abilian.i18n.VALID_LANGUAGES_CODE)
    self.config['BABEL_ACCEPT_LANGUAGES'] = languages

    self._jinja_loaders = list()
    self.register_jinja_loaders(
      jinja2.PackageLoader('abilian.web', 'templates'))

    js_filters = (('closure_js',)
                  if self.config.get('PRODUCTION', False)
                  else None)

    self._assets_bundles = {
        'css': {'options': dict(filters=('less', 'cssmin'),
                                output='style-%(version)s.min.css',)},
        'js-top': {'options': dict(output='top-%(version)s.min.js',
                                   filters=js_filters,)},
        'js': {'options': dict(output='app-%(version)s.min.js',
                               filters=js_filters)},
    }

    # bundles for JS translations
    for lang in languages:
      code = 'js-i18n-' + lang
      filename = 'lang-' + lang + '-%(version)s.min.js'
      self._assets_bundles[code] = {
          'options': dict(output=filename, filters=js_filters),
      }

    for http_error_code in (403, 404, 500):
      self.install_default_handler(http_error_code)

    with self.app_context():
      self.init_extensions()
      self.register_plugins()
      self.add_access_controller('static', allow_access_for_roles(Anonymous),
                                 endpoint=True)
      # debugtoolbar: this is needed to have it when not authenticated on a
      # private site. We cannot do this in init_debug_toolbar, since auth
      # service is not yet installed
      self.add_access_controller('debugtoolbar',
                                 allow_access_for_roles(Anonymous),)
      self.add_access_controller('_debug_toolbar.static',
                                 allow_access_for_roles(Anonymous),
                                 endpoint=True)

    self.maybe_register_setup_wizard()
    self._finalize_assets_setup()
    # At this point all models should have been imported: time to configure
    # mappers. Normally Sqlalchemy does it when needed but mappers may be
    # configured inside sa.orm.class_mapper() which hides a misconfiguration: if
    # a mapper is misconfigured its exception is swallowed by
    # class_mapper(model) results in this laconic (and misleading) message:
    # "model is not mapped"
    sa.orm.configure_mappers()

    signals.components_registered.send(self)
    self.before_first_request(self._set_current_celery_app)
    self.before_first_request(
        lambda: signals.register_js_api.send(self)
    )

    request_started.connect(self._setup_nav_and_breadcrumbs)

    # Initialize Abilian core services.
    # Must come after all entity classes have been declared.
    # Inherited from ServiceManager. Will need some configuration love later.
    if not self.config.get('TESTING', False):
      with self.app_context():
        self.start_services()
Example #11
0
    def setup(self, config):
        self.configure(config)

        # At this point we have loaded all external config files:
        # SQLALCHEMY_DATABASE_URI is definitively fixed (it cannot be defined in
        # database AFAICT), and LOGGING_FILE cannot be set in DB settings.
        self.setup_logging()

        appcontext_pushed.connect(self.install_id_generator)

        if not self.testing:
            self.init_sentry()

        # time to load config bits from database: 'settings'
        # First init required stuff: db to make queries, and settings service
        extensions.db.init_app(self)
        settings_service.init_app(self)

        self.register_jinja_loaders(jinja2.PackageLoader("abilian.web"))
        self.init_assets()
        self.install_default_handlers()

        with self.app_context():
            self.init_extensions()
            self.register_plugins()
            self.add_access_controller(
                "static", allow_access_for_roles(Anonymous), endpoint=True
            )
            # debugtoolbar: this is needed to have it when not authenticated
            # on a private site. We cannot do this in init_debug_toolbar,
            # since auth service is not yet installed.
            self.add_access_controller(
                "debugtoolbar", allow_access_for_roles(Anonymous)
            )
            self.add_access_controller(
                "_debug_toolbar.static",
                allow_access_for_roles(Anonymous),
                endpoint=True,
            )

        # TODO: maybe reenable later
        # self.maybe_register_setup_wizard()

        self._finalize_assets_setup()

        # At this point all models should have been imported: time to configure
        # mappers. Normally Sqlalchemy does it when needed but mappers may be
        # configured inside sa.orm.class_mapper() which hides a
        # misconfiguration: if a mapper is misconfigured its exception is
        # swallowed by class_mapper(model) results in this laconic
        # (and misleading) message: "model is not mapped"
        sa.orm.configure_mappers()

        signals.components_registered.send(self)

        request_started.connect(self.setup_nav_and_breadcrumbs)
        init_hooks(self)

        # Initialize Abilian core services.
        # Must come after all entity classes have been declared.
        # Inherited from ServiceManager. Will need some configuration love
        # later.
        if not self.testing:
            with self.app_context():
                self.start_services()

        setup(self)
Example #12
0
music_folder = os.path.expanduser('~/Music')

conn = None


def start_app(sender, **extra):
    global conn
    conn = sqlite3.connect(os.path.expanduser('~/.config/beets/library.db'))


def stop_app(sender, **extra):
    global conn
    conn.close()


appcontext_pushed.connect(start_app, app)
appcontext_tearing_down.connect(stop_app, app)


@app.route('/')
def index():
    return 'Welcome to Beet-Sync!'


@app.route('/albums')
def albums():
    cursor = conn.cursor()
    cursor.execute(
        'SELECT album,albumartist FROM albums ORDER BY albumartist;')
    ret_obj = []
    for row in cursor:
Example #13
0
'''
Initialize additions to the flask 'g' variable.
'''
from flask import g, appcontext_pushed
from sandhill import app


def g_set(_):
    """
    Make instance_path available for global use.
    """
    g.instance_path = app.instance_path  # pylint: disable=assigning-non-slot


appcontext_pushed.connect(g_set, app)
Example #14
0
    def setup(self, config: Optional[type]) -> None:
        self.configure(config)

        # At this point we have loaded all external config files:
        # SQLALCHEMY_DATABASE_URI is definitively fixed (it cannot be defined in
        # database AFAICT), and LOGGING_FILE cannot be set in DB settings.
        self.setup_logging()

        appcontext_pushed.connect(self.install_id_generator)

        if not self.testing:
            self.init_sentry()

        # time to load config bits from database: 'settings'
        # First init required stuff: db to make queries, and settings service
        extensions.db.init_app(self)
        settings_service.init_app(self)

        self.register_jinja_loaders(jinja2.PackageLoader("abilian.web"))
        self.init_assets()
        self.install_default_handlers()

        with self.app_context():
            self.init_extensions()
            self.register_plugins()
            self.add_access_controller("static",
                                       allow_access_for_roles(Anonymous),
                                       endpoint=True)
            # debugtoolbar: this is needed to have it when not authenticated
            # on a private site. We cannot do this in init_debug_toolbar,
            # since auth service is not yet installed.
            self.add_access_controller("debugtoolbar",
                                       allow_access_for_roles(Anonymous))
            self.add_access_controller(
                "_debug_toolbar.static",
                allow_access_for_roles(Anonymous),
                endpoint=True,
            )

        # TODO: maybe reenable later
        # self.maybe_register_setup_wizard()

        self._finalize_assets_setup()

        # At this point all models should have been imported: time to configure
        # mappers. Normally Sqlalchemy does it when needed but mappers may be
        # configured inside sa.orm.class_mapper() which hides a
        # misconfiguration: if a mapper is misconfigured its exception is
        # swallowed by class_mapper(model) results in this laconic
        # (and misleading) message: "model is not mapped"
        sa.orm.configure_mappers()

        signals.components_registered.send(self)

        request_started.connect(self.setup_nav_and_breadcrumbs)
        init_hooks(self)

        # Initialize Abilian core services.
        # Must come after all entity classes have been declared.
        # Inherited from ServiceManager. Will need some configuration love
        # later.
        if not self.testing:
            with self.app_context():
                self.start_services()

        setup(self)