Function to return celery-app. Works only if celery installed.
    :param name: Application name
    :param kwargs: overrided env-settings
    :return: Celery-app object
326371
def get_celery_app(name=None, **kwargs):  # nocv
    # pylint: disable=import-error
    '''
    
    '''
    from celery import Celery
    prepare_environment(**kwargs)
    name = name or os.getenv("VST_PROJECT")
    celery_app = Celery(name)
    celery_app.config_from_object('django.conf:settings', namespace='CELERY')
    celery_app.autodiscover_tasks()
    return celery_app
715122
def get_app(config):
    
    # First, disable debug. It will be enabled in the configuration, later.
    web.config.debug = False

    config = _put_configuration_defaults(config)

    mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost'))
    database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')]
    gridfs = GridFS(database)

    # Init database if needed
    db_version = database.db_version.find_one({})
    if db_version is None:
        database.submissions.ensure_index([("username", pymongo.ASCENDING)])
        database.submissions.ensure_index([("courseid", pymongo.ASCENDING)])
        database.submissions.ensure_index([("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)])
        database.submissions.ensure_index([("submitted_on", pymongo.DESCENDING)])  # sort speed
        database.user_tasks.ensure_index(
            [("username", pymongo.ASCENDING), ("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)],
            unique=True)
        database.user_tasks.ensure_index([("username", pymongo.ASCENDING), ("courseid", pymongo.ASCENDING)])
        database.user_tasks.ensure_index([("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)])
        database.user_tasks.ensure_index([("courseid", pymongo.ASCENDING)])
        database.user_tasks.ensure_index([("username", pymongo.ASCENDING)])

    appli = CookieLessCompatibleApplication(MongoStore(database, 'sessions'))

    # Init gettext
    available_languages = {
        "en": "English",
        "fr": "Français"
    }

    for lang in available_languages.keys():
        appli.add_translation(lang, gettext.translation('messages', get_root_path() + '/frontend/i18n', [lang]))

    builtins.__dict__['_'] = appli.gettext

    if config.get("maintenance", False):
        template_helper = TemplateHelper(PluginManager(), None,
                                         'frontend/templates',
                                         'frontend/templates/layout',
                                         'frontend/templates/layout_lti',
                                         config.get('use_minified_js', True))
        template_helper.add_to_template_globals("get_homepath", appli.get_homepath)
        template_helper.add_to_template_globals("_", _)
        appli.template_helper = template_helper
        appli.init_mapping(urls_maintenance)
        return appli.wsgifunc(), appli.stop

    default_allowed_file_extensions = config['allowed_file_extensions']
    default_max_file_size = config['max_file_size']

    zmq_context, __ = start_asyncio_and_zmq(config.get('debug_asyncio', False))

    # Init the different parts of the app
    plugin_manager = PluginManager()

    # Create the FS provider
    if "fs" in config:
        fs_provider = filesystem_from_config_dict(config["fs"])
    else:
        task_directory = config["tasks_directory"]
        fs_provider = LocalFSProvider(task_directory)

    default_problem_types = {
        problem_type.get_type(): problem_type for problem_type in [DisplayableCodeProblem,
                                                                   DisplayableCodeSingleLineProblem,
                                                                   DisplayableFileProblem,
                                                                   DisplayableMultipleChoiceProblem,
                                                                   DisplayableMatchProblem]
    }

    course_factory, task_factory = create_factories(fs_provider, default_problem_types, plugin_manager, WebAppCourse, WebAppTask)

    user_manager = UserManager(appli.get_session(), database, config.get('superadmins', []))

    update_pending_jobs(database)

    client = create_arch(config, fs_provider, zmq_context, course_factory)

    lti_outcome_manager = LTIOutcomeManager(database, user_manager, course_factory)

    submission_manager = WebAppSubmissionManager(client, user_manager, database, gridfs, plugin_manager, lti_outcome_manager)

    template_helper = TemplateHelper(plugin_manager, user_manager, 'frontend/templates',
                                     'frontend/templates/layout',
                                     'frontend/templates/layout_lti',
                                     config.get('use_minified_js', True))



    # Init web mail
    smtp_conf = config.get('smtp', None)
    if smtp_conf is not None:
        web.config.smtp_server = smtp_conf["host"]
        web.config.smtp_port = int(smtp_conf["port"])
        web.config.smtp_starttls = bool(smtp_conf.get("starttls", False))
        web.config.smtp_username = smtp_conf.get("username", "")
        web.config.smtp_password = smtp_conf.get("password", "")
        web.config.smtp_sendername = smtp_conf.get("sendername", "no-reply@ingnious.org")

    # Add some helpers for the templates
    template_helper.add_to_template_globals("_", _)
    template_helper.add_to_template_globals("str", str)
    template_helper.add_to_template_globals("available_languages", available_languages)
    template_helper.add_to_template_globals("get_homepath", appli.get_homepath)
    template_helper.add_to_template_globals("allow_registration", config.get("allow_registration", True))
    template_helper.add_to_template_globals("user_manager", user_manager)
    template_helper.add_to_template_globals("default_allowed_file_extensions", default_allowed_file_extensions)
    template_helper.add_to_template_globals("default_max_file_size", default_max_file_size)
    template_helper.add_other("course_admin_menu",
                              lambda course, current: course_admin_utils.get_menu(course, current, template_helper.get_renderer(False),
                                                                                  plugin_manager, user_manager))
    template_helper.add_other("preferences_menu",
                              lambda current: preferences_utils.get_menu(appli, current, template_helper.get_renderer(False),
                                                                                 plugin_manager, user_manager))

    # Not found page
    appli.notfound = lambda: web.notfound(template_helper.get_renderer().notfound('Page not found'))

    # Enable stacktrace display if needed
    web_debug = config.get('web_debug', False)
    appli.internalerror = internalerror_generator(template_helper.get_renderer(False))
    if web_debug is True:
        web.config.debug = True
        appli.internalerror = debugerror
    elif isinstance(web_debug, str):
        web.config.debug = False
        appli.internalerror = emailerrors(web_debug, appli.internalerror)

    # Insert the needed singletons into the application, to allow pages to call them
    appli.plugin_manager = plugin_manager
    appli.course_factory = course_factory
    appli.task_factory = task_factory
    appli.submission_manager = submission_manager
    appli.user_manager = user_manager
    appli.template_helper = template_helper
    appli.database = database
    appli.gridfs = gridfs
    appli.default_allowed_file_extensions = default_allowed_file_extensions
    appli.default_max_file_size = default_max_file_size
    appli.backup_dir = config.get("backup_directory", './backup')
    appli.webterm_link = config.get("webterm", None)
    appli.lti_outcome_manager = lti_outcome_manager
    appli.allow_registration = config.get("allow_registration", True)
    appli.allow_deletion = config.get("allow_deletion", True)
    appli.available_languages = available_languages
    appli.welcome_page = config.get("welcome_page", None)
    appli.static_directory = config.get("static_directory", "./static")
    appli.webdav_host = config.get("webdav_host", None)

    # Init the mapping of the app
    appli.init_mapping(urls)

    # Loads plugins
    plugin_manager.load(client, appli, course_factory, task_factory, database, user_manager, submission_manager, config.get("plugins", []))

    # Start the inginious.backend
    client.start()

    return appli.wsgifunc(), lambda: _close_app(appli, mongo_client, client)
1056704
def get_menu(self, name):
        
        if self.menubar is None:
            raise ValueError("No menu bar configured")
        return self.menubar.get_menu(name)
587914
def init_config(self, app):
        
        try:
            pkg_resources.get_distribution('celery')
            app.config.setdefault(
                "ACCOUNTS_USE_CELERY", not (app.debug or app.testing))
        except pkg_resources.DistributionNotFound:  # pragma: no cover
            app.config.setdefault("ACCOUNTS_USE_CELERY", False)

        # Register Invenio legacy password hashing
        register_crypt_handler(InvenioAesEncryptedEmail)

        # Change Flask defaults
        app.config.setdefault(
            'SESSION_COOKIE_SECURE',
            not app.debug
        )

        # Change Flask-Security defaults
        app.config.setdefault(
            'SECURITY_PASSWORD_SALT',
            app.config['SECRET_KEY']
        )

        # Set JWT secret key
        app.config.setdefault(
            'ACCOUNTS_JWT_SECRET_KEY',
            app.config.get(
                'ACCOUNTS_JWT_SECRET_KEY',
                app.config.get('SECRET_KEY')
            )
        )

        config_apps = ['ACCOUNTS', 'SECURITY_']
        for k in dir(config):
            if any([k.startswith(prefix) for prefix in config_apps]):
                app.config.setdefault(k, getattr(config, k))

        # Set Session KV store
        if app.config.get('ACCOUNTS_SESSION_REDIS_URL'):
            import redis
            from simplekv.memory.redisstore import RedisStore

            session_kvstore = RedisStore(redis.StrictRedis.from_url(
                app.config['ACCOUNTS_SESSION_REDIS_URL']))
        else:
            from simplekv.memory import DictStore

            session_kvstore = DictStore()

        self.kvsession_extension = KVSessionExtension(
            session_kvstore, app)
337497
def wsgi_app(self, environ, start_response):
        """"""
        @_LOCAL_MANAGER.middleware
        def _wrapped_app(environ, start_response):
            request = Request(environ)
            setattr(_local, _CURRENT_REQUEST_KEY, request)
            response = self._dispatch_request(request)
            return response(environ, start_response)
        return _wrapped_app(environ, start_response)
612200
def get_service(self, name):
        
        self._convert_connected_app()
        if not self.project_config.services or name not in self.project_config.services:
            self._raise_service_not_valid(name)
        if name not in self.services:
            self._raise_service_not_configured(name)

        return self._get_service(name)
1289208
def call(self, name, options=None, o=None):
        
        if options is None:
            options = []

        command = self.get_application().find(name)

        options = [('command', command.get_name())] + options

        return command.run(ListInput(options), o)
52039
def get_by_name(config=None, name=None, name_label='name'):
        

        if name is None:
            raise SyntaxError(
                'Deployment: name: [ {0} ] cannot be None.'.format(name))
        if not isinstance(name, str):
            raise SyntaxError(
                'Deployment: name: [ {0} ] must be a string.'.format(name))

        if config is not None and not isinstance(config, K8sConfig):
            raise SyntaxError(
                'Deployment: config: [ {0} ] must be a K8sConfig'.format(config))

        deps = K8sDeployment(config=config, name=name).list(labels={
            name_label: name
        })

        return deps
321444
def get_app(self, reference_app=None):
        """"""

        if reference_app is not None:
            return reference_app

        if current_app:
            return current_app._get_current_object()

        if self.app is not None:
            return self.app

        raise RuntimeError(
            'No application found. Either work inside a view function or push'
            ' an application context. See'
            ' http://flask-sqlalchemy.pocoo.org/contexts/.'
        )
809057
def has_app(app_name):
    
    if DJANGO_VERSION >= (1, 7):
        from django.apps import apps
        return apps.is_installed(app_name)
    else:
        from django.conf import settings

        return app_name in settings.INSTALLED_APPS
1006133
def make_default_app_wrapper(name):
    '''  '''
    @functools.wraps(getattr(Bottle, name))
    def wrapper(*a, **ka):
        return getattr(app(), name)(*a, **ka)
    return wrapper
8009
def context(name):
    ''''''
    def wrapper(func):
        g.theme.context_processors[name] = func
        return func
    return wrapper
927706
def get_config(cls, key, default=None):
        
        return cls._app.config.get(key, default)
538792
def get_app_key(self):
        
        if self.app_key is None:
            if os.environ.get(self.username):
                self.app_key = os.environ.get(self.username)
            else:
                raise AppKeyError(self.username)
1299806
def load_menus(c):
        

        # we don't need to do this more than once
        if c.loaded:
            return

        # Fetch all installed app names
        app_names = settings.INSTALLED_APPS
        if apps:
            app_names = [
                app_config.name
                for app_config in apps.get_app_configs()
            ]

        # loop through our INSTALLED_APPS
        for app in app_names:
            # skip any django apps
            if app.startswith("django."):
                continue

            menu_module = '%s.menus' % app
            try:
                __import__(menu_module, fromlist=["menu", ])
            except ImportError:
                pass

        c.loaded = True
820516
def install(self, **kwargs):
        
        if self._dxid is not None:
            return dxpy.api.app_install(self._dxid, **kwargs)
        else:
            return dxpy.api.app_install('app-' + self._name, alias=self._alias, **kwargs)
858623
def router(name, args, kwargs, options, task=None, **kw):
    '''
    
    '''
    # Fetch task by name if necessary
    task = task or celery.tasks.get(name)
    if not task:
        return
    # Single route param override everything
    if task.route:
        queue = task.route.split('.', 1)[0]
        return {'queue': queue, 'routing_key': task.route}
    # queue parameter, routing_key computed if not present
    if task.default_queue:
        key = task.default_routing_key
        key = key or '{0.default_queue}.{0.name}'.format(task)
        return {'queue': task.default_queue, 'routing_key': key}
    # only routing_key, queue should not be returned to fallback on default
    elif task.default_routing_key:
        return {'routing_key': task.default_routing_key}