Ejemplo n.º 1
0
    def __init__(self, router: Router, statics: StaticFiles,
                 settings: Settings) -> None:
        template_settings = settings.get('TEMPLATES', self.DEFAULT_SETTINGS)

        loaders = []  # type: typing.List[jinja2.BaseLoader]
        if template_settings.get('PACKAGE_DIRS'):
            loaders.extend([
                jinja2.PrefixLoader({
                    package_dir:
                    jinja2.PackageLoader(package_dir, 'templates')
                }) for package_dir in template_settings['PACKAGE_DIRS']
            ])
        if template_settings.get('ROOT_DIR'):
            loaders.append(
                jinja2.FileSystemLoader(template_settings['ROOT_DIR']))

        loader = jinja2.ChoiceLoader(loaders)
        env = jinja2.Environment(loader=loader)
        env.globals['reverse_url'] = router.reverse_url
        env.globals['static_url'] = statics.get_url
        self._env = env
Ejemplo n.º 2
0
def render_template(loader, template_name, glob_helper=lambda f: [], clock=time.Clock):
    macros = """
        {% macro collect(parts) -%}
            {% set comma = joiner() %}
            {% for part in glob(parts) %}
                {{ comma() }}
                {% include part %}
            {% endfor %}
        {%- endmacro %}
    """

    # place helpers dict loader first to prevent users from overriding our macros.
    env = jinja2.Environment(
        loader=jinja2.ChoiceLoader([jinja2.DictLoader({"rally.helpers": macros}), loader])
    )
    env.globals["now"] = clock.now()
    env.globals["glob"] = glob_helper
    env.filters["days_ago"] = time.days_ago
    template = env.get_template(template_name)

    return template.render()
def test_optional_nullable():
    from openapi_python_client.parser.properties import DateProperty

    prop = DateProperty(
        name="a_prop",
        required=False,
        nullable=True,
        default=None,
    )
    here = Path(__file__).parent
    templates_dir = here.parent.parent.parent.parent / "openapi_python_client" / "templates"

    env = jinja2.Environment(loader=jinja2.ChoiceLoader([
        jinja2.FileSystemLoader(here),
        jinja2.FileSystemLoader(templates_dir)
    ]))

    template = env.get_template("date_property_template.py")
    content = template.render(property=prop)
    expected = here / "optional_nullable.py"
    assert content == expected.read_text()
Ejemplo n.º 4
0
    def __init__(self, csr_data_dir=None):
        # chain loaders:
        # 1) csr_data_dir/templates
        # 2) /etc/ipa/csrgen/templates
        # 3) ipaclient/csrgen/templates
        loaders = []
        if csr_data_dir is not None:
            loaders.append(jinja2.FileSystemLoader(
                os.path.join(csr_data_dir, 'templates'))
            )
        loaders.append(jinja2.FileSystemLoader(
            os.path.join(api.env.confdir, 'csrgen/templates'))
        )
        loaders.append(jinja2.PackageLoader('ipaclient', 'csrgen/templates'))

        self.jinja2 = jinja2.sandbox.SandboxedEnvironment(
            loader=jinja2.ChoiceLoader(loaders),
            extensions=[jinja2.ext.ExprStmtExtension, IPAExtension],
            keep_trailing_newline=True, undefined=IndexableUndefined)

        self.passthrough_globals = {}
Ejemplo n.º 5
0
def create_app(config=None, environment=None):
    logger.info(f"config : {config}")
    logger.info(f"environment: {environment}")

    app = BlogsleyFlask.create(config, environment)

    #Configure Jinja2
    my_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader(['blogsley_flask/templates']),
        ])
    app.jinja_loader = my_loader

    #Configure Login
    from blogsley_flask.user import User
    @__blogsley__.login.user_loader
    def load_user(id):
        return User.query.get(int(id))
        
    return app
    
Ejemplo n.º 6
0
def test_jinja_templates(network, args, verify=True):
    primary, _ = network.find_primary()

    new_user_local_id = "bob"
    new_user = network.create_user(new_user_local_id, args.participants_curve)

    with primary.client(new_user_local_id) as c:
        r = c.post("/app/log/private", {"id": 42, "msg": "New user test"})
        assert r.status_code == http.HTTPStatus.UNAUTHORIZED.value

    template_loader = jinja2.ChoiceLoader(
        [
            jinja2.FileSystemLoader(args.jinja_templates_path),
            jinja2.FileSystemLoader(os.path.dirname(new_user.cert_path)),
        ]
    )
    template_env = jinja2.Environment(
        loader=template_loader, undefined=jinja2.StrictUndefined
    )

    proposal_template = template_env.get_template("set_user_proposal.json.jinja")
    proposal_body = proposal_template.render(cert=os.path.basename(new_user.cert_path))
    proposal = network.consortium.get_any_active_member().propose(
        primary, proposal_body
    )

    ballot_template = template_env.get_template("ballot.json.jinja")
    ballot_body = ballot_template.render(**json.loads(proposal_body))
    network.consortium.vote_using_majority(primary, proposal, ballot_body)

    with primary.client(new_user_local_id) as c:
        r = c.post("/app/log/private", {"id": 42, "msg": "New user test"})
        assert r.status_code == http.HTTPStatus.OK.value

    network.consortium.remove_user(primary, new_user.service_id)
    with primary.client(new_user_local_id) as c:
        r = c.get("/app/log/private")
        assert r.status_code == http.HTTPStatus.UNAUTHORIZED.value

    return network
Ejemplo n.º 7
0
    def init_app(self, app, socketio=None, **kwargs):
        app.jinja_env.add_extension(MeldTag)
        app.jinja_env.add_extension(MeldScriptsTag)

        # Load templates from template dir or app/meld/templates
        custom_template_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader(os.path.join(app.root_path, 'meld/templates')),
        ])

        app.jinja_loader = custom_template_loader
        if socketio:
            app.socketio = socketio
        else:
            app.socketio = SocketIO(app, **kwargs)

        meld_dir = app.config.get("MELD_COMPONENT_DIR", None)
        if meld_dir:
            if not os.path.isabs(meld_dir):
                directory = os.path.abspath(os.path.join(app.root_path, meld_dir))
                app.config["MELD_COMPONENT_DIR"] = directory

        if not app.config.get("SECRET_KEY"):
            raise RuntimeError(
                "The Flask-Meld requires the 'SECRET_KEY' config " "variable to be set"
            )

        @app.route("/meld_js_src/<path:filename>")
        def meld_static_file(filename):
            return self.send_static_file(filename)

        @app.socketio.on("meld-message")
        def meld_message(message):
            """meldID, action, componentName"""
            result = process_message(message)
            app.socketio.emit("meld-response", result)

        @app.socketio.on("meld-init")
        def meld_init(message):
            return process_init(message)
Ejemplo n.º 8
0
def init_webapp(app, db):
    print 'Initializing MLN webapp...'

    mlnApp.app = app
    # use html templates from mln app
    mln_loader = jinja2.ChoiceLoader([
        mlnApp.app.jinja_loader,
        jinja2.FileSystemLoader(
            ['/opt/practools/tools/pracmln/webmln/gui/templates']),
    ])
    mlnApp.app.jinja_loader = mln_loader
    mlnApp.app.config[
        'MLN_STATIC_PATH'] = '/opt/practools/tools/pracmln/webmln/gui/build'

    # settings for fileuploads and logging
    mlnApp.app.config['ALLOWED_EXTENSIONS'] = {'mln', 'db', 'pracmln', 'emln'}
    mlnApp.app.config['UPLOAD_FOLDER'] = '/home/ros/pracfiles'
    mlnApp.app.config['MLN_ROOT_PATH'] = '/opt/practools/tools/pracmln'
    mlnApp.app.config['EXAMPLES_FOLDER'] = os.path.join(
        mlnApp.app.config['MLN_ROOT_PATH'], 'examples')
    mlnApp.app.config['LOG_FOLDER'] = os.path.join('/home/ros/pracfiles/mln',
                                                   'log')

    if not os.path.exists(mlnApp.app.config['LOG_FOLDER']):
        os.mkdir(mlnApp.app.config['LOG_FOLDER'])

    ulog = logging.getLogger('userstats')
    ulog.setLevel(logging.INFO)
    formatter = logging.Formatter("%(message)s,")
    filelogger = FileHandler(
        os.path.join(mlnApp.app.config['LOG_FOLDER'], "userstats.json"))
    filelogger.setFormatter(formatter)
    ulog.addHandler(filelogger)

    print 'Registering MLN routes...'
    from webmln.gui.pages import learning
    from webmln.gui.pages import inference
    from webmln.gui.pages import views
    from webmln.gui.pages import fileupload
    from webmln.gui.pages import utils
Ejemplo n.º 9
0
    def __init__(self):
        self.async_mode = 'eventlet' # None
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 'secret!'
        thread = None
        self.socketio = SocketIO(self.app, async_mode=self.async_mode, logger=True, engineio_logger=True)
        template_loader = jinja2.ChoiceLoader([self.app.jinja_loader,
                                               jinja2.PackageLoader('mTree', 'development/development_templates'),
                                               ])
        self.app.jinja_loader = template_loader

        #self.app.config['BASIC_AUTH_USERNAME'] = '******'
        #self.app.config['BASIC_AUTH_PASSWORD'] = '******'

        self.basic_auth = BasicAuth(self.app)

        self.mTree_configuration = MTreeConfiguration()
        self.subject_directory = SubjectDirectory()


        self.add_routes()
        # self.scheduler = APScheduler()
        # self.scheduler.init_app(self.app)
        # self.scheduler.start()
        #self.scheduler.add_listener(self.my_listener, events.EVENT_ALL)
        self.app.register_blueprint(development_area, url_prefix='/')

        self.app.register_blueprint(subject_area, url_prefix='/subjects')

        self.subject_container = None #SubjectContainer()

        #self.actor_system = ActorSystemConnector()

        # attempts at logger adding...
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        handler = RequestsHandler(emit)
        handler.setLevel(logging.INFO)
        myfilter = MyFilter()
        handler.addFilter(myfilter)
Ejemplo n.º 10
0
async def setup(app):
    procs = [request_processor]
    # setup Jinja2 template renderer
    app_loaders = [
        jinja2.FileSystemLoader(os.path.join(settings.BASE_DIR, "app/views_min/")),
        jinja2.FileSystemLoader(os.path.join(settings.BASE_DIR, "app/views/")),
        jinja2.PackageLoader("aioweb", "views/")
    ]
    for app_name in settings.APPS:
        try:
            app_loaders.append(jinja2.PackageLoader(app_name, "app/views"))
        except ImportError as e:
            pass

    env = jinja2.Environment(
        loader=jinja2.ChoiceLoader(app_loaders),
        enable_async=True,
        trim_blocks=True,
        lstrip_blocks=True,
        extensions=[
            DjangoStatic,
            DjangoUrl,
            DjangoNow,
            DjangoTrans
        ])

    env.globals['settings'] = settings
    env.globals['app'] = app

    app[APP_KEY] = env
    app[APP_CONTEXT_PROCESSORS_KEY] = procs
    app.middlewares.append(context_processors_middleware)

    try:
        mod = importlib.import_module("app")
        setup = getattr(mod, 'setup_template')
        await awaitable(setup(env))
    except (ImportError, AttributeError) as e:
        pass
Ejemplo n.º 11
0
def jinja_choice_loader(loader):
    return jinja2.ChoiceLoader([loader,
                jinja2.DictLoader({
                    'snippets/per_lab/lab_env/lab.test-kickstart.invalid': '''
cat << EOF > /etc/profile.d/rh-env.sh
export LAB_CONTROLLER=lab.test-kickstart.invalid
export DUMPSERVER=netdump.test-kickstart.invalid
export NFSSERVERS="RHEL3,rhel3-nfs.test-kickstart.invalid:/export/home RHEL4,rhel4-nfs.test-kickstart.invalid:/export/home RHEL5,rhel5-nfs.test-kickstart.invalid:/export/home RHEL6,rhel6-nfs.test-kickstart.invalid:/export/home NETAPP, SOLARIS,"
export LOOKASIDE=http://download.test-kickstart.invalid/lookaside/
export BUILDURL=http://download.test-kickstart.invalid
EOF
cat << EOF > /etc/profile.d/rh-env.csh
setenv LAB_CONTROLLER lab.test-kickstart.invalid
setenv DUMPSERVER netdump.test-kickstart.invalid
setenv NFSSERVERS "RHEL3,rhel3-nfs.test-kickstart.invalid:/export/home RHEL4,rhel4-nfs.test-kickstart.invalid:/export/home RHEL5,rhel5-nfs.test-kickstart.invalid:/export/home RHEL6,rhel6-nfs.test-kickstart.invalid:/export/home NETAPP, SOLARIS,"
setenv LOOKASIDE http://download.test-kickstart.invalid/lookaside/
setenv BUILDURL http://download.test-kickstart.invalid
EOF
''',
                    'snippets/per_system/packages/bz728410-system-with-packages':
                        'special-weird-driver-package\n',
                })])
Ejemplo n.º 12
0
 def _setup_jinja(self):
     self.add_template_filter(datetime_short)
     self.add_template_filter(datetime_long)
     self.add_template_filter(date_header)
     self.add_template_filter(plain_text)
     self.add_template_filter(time_short)
     self.add_template_filter(date_short)
     self.add_template_filter(word_count)
     self.add_template_filter(char_count)
     self.add_template_global(get_company_sidenavs, 'sidenavs')
     self.add_template_global(sidenavs_by_names)
     self.add_template_global(sidenavs_by_group)
     self.add_template_global(newsroom_config)
     self.add_template_global(is_admin)
     self.add_template_global(get_initial_notifications)
     self.add_template_global(hash_string, 'hash')
     self.add_template_global(get_date, 'get_date')
     self.add_template_global(self.settings_apps, 'settings_apps')
     self.jinja_loader = jinja2.ChoiceLoader([
         jinja2.FileSystemLoader('theme'),
         jinja2.FileSystemLoader(self.template_folder),
     ])
Ejemplo n.º 13
0
  def init_app(self, app):
    """Initializes the App.

    Args:
        app (TYPE): Description

    Returns:
        TYPE: Description
    """

    config = app.config.copy()
    self.debug        = config.get('PONYWHOOSH_DEBUG', self.debug)
    self.indexes_path = config.get('PONYWHOOSH_INDEXES_PATH',  self.indexes_path)
    self.search_string_min_len = config.get('PONYWHOOSH_MIN_STRING_LEN', self.search_string_min_len)
    self.template_path  = config.get('PONYWHOOSH_TEMPLATE_PATH', self.template_path)
    self.url_route      = config.get('PONYWHOOSH_URL_ROUTE', self.url_route)
    self.writer_timeout = config.get('PONYWHOOSH_WRITER_TIMEOUT', self.writer_timeout)

    if self.debug:
      print('PONYWHOOSH_DEBUG: ', self.debug)
      print('PONYWHOOSH_INDEXES_PATH : ', self.indexes_path)
      print('PONYWHOOSH_MIN_STRING_LEN : ', self.search_string_min_len)
      print('PONYWHOOSH_TEMPLATE_PATH: ', self.template_path)
      print('PONYWHOOSH_URL_ROUTE: ',  self.url_route)
      print('PONYWHOOSH_WRITER_TIMEOUT: ', self.writer_timeout)

    loader = jinja2.ChoiceLoader([
        app.jinja_loader
      , jinja2.FileSystemLoader(self.template_path)
    ])

    app.jinja_loader = loader
    app.add_url_rule(
        self.url_route
      , view_func=IndexView.as_view(self.url_route
        , pw=self
        , action_url_form=self.url_route
        )
    )
Ejemplo n.º 14
0
    def _build_loader(self, extra_paths=None):
        # Paths for resolving template file locations
        non_prefix_template_paths = [
            os.path.normpath(
                os.path.join(os.path.dirname(monkey.__file__),
                             '../templates')),
            os.path.normpath(
                os.path.join(os.path.dirname(monkey.__file__), './templates'))
        ]
        prefix_paths = {
            'app':
            os.path.join(os.path.dirname(monkey.__file__), '../templates'),
            'framework':
            os.path.join(os.path.dirname(monkey.__file__), './templates')
        }

        # Extra (plugin) paths
        if extra_paths:
            for x in extra_paths:
                if not x[1]:  # non prefixed
                    non_prefix_template_paths += x[0]

            prefix_paths.update({x[1]: x[0] for x in extra_paths if x[1]})

        # Theme Paths
        if self.theme:
            non_prefix_template_paths = [
                os.path.normpath(os.path.join(x, './themes/%s/' % self.theme))
                for x in non_prefix_template_paths
            ] + non_prefix_template_paths

        loader = jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(non_prefix_template_paths),
            jinja2.PrefixLoader({
                k: jinja2.FileSystemLoader(v)
                for k, v in prefix_paths.iteritems()
            })
        ])
        return loader
Ejemplo n.º 15
0
Archivo: ext.py Proyecto: jma/rero-ils
    def __init__(self, app=None):
        """RERO ILS App module."""
        if app:
            self.init_app(app)
            # force to load ils template before others
            # it is require for Flask-Security see:
            # https://pythonhosted.org/Flask-Security/customizing.html#emails
            ils_loader = jinja2.ChoiceLoader([
                jinja2.PackageLoader('rero_ils', 'templates'),
                app.jinja_loader
            ])
            app.jinja_loader = ils_loader

            # register filters
            app.add_template_filter(format_date_filter, name='format_date')
            app.add_template_global(node_assets, name='node_assets')
            app.add_template_filter(to_pretty_json, name='tojson_pretty')
            app.add_template_filter(text_to_id, name='text_to_id')
            app.add_template_filter(jsondumps, name='jsondumps')
            app.add_template_filter(empty_data, name='empty_data')
            app.jinja_env.add_extension('jinja2.ext.do')
            self.register_signals(app)
Ejemplo n.º 16
0
    def __init__(self):
        self._libraries = []

        loader = jinja2.ChoiceLoader(self._get_loaders())
        options = self._get_options()

        super(Environment, self).__init__(
            extensions=options['extensions'],
            loader=loader,
            trim_blocks=True,
            autoescape=True,
            auto_reload=settings.DEBUG,
        )

        # Note: options already includes Jinja2's own builtins (with
        # the proper priority), so we want to assign to these attributes.
        self.filters = options['filters'].copy()
        self.globals = options['globals'].copy()
        self.tests = options['tests'].copy()
        for key, value in options['attrs'].items():
            setattr(self, key, value)

        # Set the environment in all libraries found.
        for library in self._libraries:
            library.set_env(self)

        # Hook Jinja's i18n extension up to Django's translation backend
        # if i18n is enabled; note that we differ here from Django, in that
        # Django always has it's i18n functionality available (that is, if
        # enabled in a template via {% load %}), but uses a null backend if
        # the USE_I18N setting is disabled. Jinja2 provides something similar
        # (install_null_translations), but instead we are currently not
        # enabling the extension at all when USE_I18N=False.
        # While this is basically an incompatibility with Django, currently
        # the i18n tags work completely differently anyway, so for now, I
        # don't think it matters.
        if settings.USE_I18N:
            from django.utils import translation
            self.install_gettext_translations(translation)
Ejemplo n.º 17
0
    def __init__(self, import_name=__package__, config=None, **kwargs):
        if not getattr(self, 'settings'):
            self.settings = flask.Config('.')

        super(NewsroomNewsAPI, self).__init__(import_name=import_name,
                                              config=config,
                                              **kwargs)

        template_folder = os.path.abspath(
            os.path.join(API_DIR, '../../templates'))

        self.add_template_filter(datetime_short)
        self.add_template_filter(datetime_long)
        self.add_template_filter(date_header)
        self.add_template_filter(plain_text)
        self.add_template_filter(time_short)
        self.add_template_filter(date_short)
        self.add_template_filter(word_count)
        self.add_template_filter(char_count)
        self.jinja_loader = jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(template_folder),
        ])
Ejemplo n.º 18
0
Archivo: atgu.py Proyecto: saponas/hail
def run():
    app = web.Application()

    setup_aiohttp_session(app)

    aiohttp_jinja2.setup(app,
                         loader=jinja2.ChoiceLoader(
                             [jinja2.PackageLoader('atgu')]))

    app.add_routes(routes)
    app.router.add_get("/metrics", server_stats)

    app.on_startup.append(on_startup)
    app.on_cleanup.append(on_cleanup)

    web.run_app(
        deploy_config.prefix_application(app, 'atgu'),
        host='0.0.0.0',
        port=5000,
        access_log_class=AccessLogger,
        ssl_context=internal_server_ssl_context(),
    )
Ejemplo n.º 19
0
def setup_jinja2(template_dirs, auto_reload):
    """Setup a jinja2 env (https://www.starlette.io/templates/)"""
    @jinja2.contextfunction
    def url_for(context, name, **path_params):
        request = context['request']
        return request.url_for(name, **path_params)

    # first check for template overrides on the same level above the modual.
    # check lamia defaults if nothing is found
    loader = jinja2.ChoiceLoader([
        jinja2.FileSystemLoader(template_dirs),
        jinja2.PackageLoader('lamia')
    ])
    env = jinja2.Environment(
        loader=loader,
        autoescape=True,
        auto_reload=auto_reload,
        extensions=['jinja2.ext.i18n'],
    )
    env.install_gettext_translations(EN)  # pylint: disable=no-member
    env.globals['url_for'] = url_for
    return env
Ejemplo n.º 20
0
def get_jinja2_loader(template_dir=None):
    """Inspect the template directory and set up appropriate loader.

    :param target_dir: Limit template loading to this directory.
    :type target_dir: str
    :returns: Jinja2 loader
    :rtype: jinja2.loaders.BaseLoader
    """
    if template_dir:
        return jinja2.FileSystemLoader(template_dir)
    else:
        template_dir = get_overlay_template_dir()
    provider_template_dir = os.path.join(template_dir,
                                         zaza.controller.get_cloud_type())
    if (os.path.exists(provider_template_dir)
            and os.path.isdir(provider_template_dir)):
        return jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(provider_template_dir),
            jinja2.FileSystemLoader(template_dir),
        ])
    else:
        return jinja2.FileSystemLoader(template_dir)
Ejemplo n.º 21
0
def load_devicetype_template(device_type_name):
    """
    Loads the bare device-type template as a python dictionary object for
    representation within the device_type templates.
    No device-specific details are parsed - default values only, so some
    parts of the dictionary may be unexpectedly empty. Not to be used when
    rendering device configuration for a testjob.
    :param device_type_name: DeviceType.name (string)
    :param path: optional alternative path to templates
    :return: None or a dictionary of the device type template.
    """
    path = os.path.dirname(Device.CONFIG_PATH)
    type_loader = jinja2.FileSystemLoader([os.path.join(path, 'device-types')])
    env = jinja2.Environment(loader=jinja2.ChoiceLoader([type_loader]),
                             trim_blocks=True)
    try:
        template = env.get_template("%s.jinja2" % device_type_name)
    except jinja2.TemplateNotFound:
        return None
    if not template:
        return None
    return yaml.load(template.render())
Ejemplo n.º 22
0
    def load_project(self, project):
        self.project = self._load_project_from_dir(project)
        if not self.project:
            self.project = AbstractProject()
        self.project.directory = project

        def file_load(name):
            """
            The default FileSystemLoader doesn't load files specified
            by absolute paths or paths that include '..' - therefore
            we provide a custom fallback function that handles this.
            """
            name = os.path.abspath(name)
            try:
                with open(name, 'rb') as f:
                    return f.read().decode('utf-8')
            except Exception:
                raise jinja2.TemplateNotFound(name)

        def string_load(name):
            """
            Allow specifying a string instead of template to be able
            to return expanded config/specs/...
            """
            if name.startswith(('{{', '{%')):
                return name
            raise jinja2.TemplateNotFound(name)

        loader = jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(self.pm_tpl.get_path()),
            jinja2.FunctionLoader(string_load),
            jinja2.FunctionLoader(file_load),
        ])

        self.project.tplgen = jinja2.Environment(loader=loader,
                                                 **self.jinjaenv_args)

        self.project.abstract_initialize()
Ejemplo n.º 23
0
    def __init__(self, implementation):
        Flask.__init__(self, __name__, static_url_path='/common_static')

        self.jinja_loader = jinja2.ChoiceLoader(
            [self.jinja_loader,
             jinja2.PrefixLoader({}, delimiter=".")])

        sidebar_links = []

        def import_dir(path, prefix):
            for _, package, _ in pkgutil.walk_packages([path]):
                if package[:4] == 'mod_' or package == implementation:
                    for _, module, _ in pkgutil.iter_modules([path + package]):
                        if module == 'controller':
                            controller = importlib.import_module(prefix + '.' +
                                                                 package +
                                                                 '.' + module)
                            if hasattr(controller, 'mod'):
                                self.register_blueprint(controller.mod)
                                print('Registering:',
                                      prefix + '.' + package + '.' + module)

        path = os.path.dirname(__file__) + '/'
        import_dir(path, 'web_apps')
        import_dir(path + implementation + '/', 'web_apps.' + implementation)

        @self.errorhandler(404)
        def not_found(error):
            return render_template('404.html'), 404

        @self.teardown_appcontext
        def close_db(error):
            if hasattr(g, 'cursor'):
                g.cursor.close()
            if hasattr(g, 'database'):
                g.database.close()
            if hasattr(g, 'clientsDB'):
                g.clientsDB.close()
Ejemplo n.º 24
0
    def _init_templates(self):
        # load user defined templates
        if self.config['LOCAL_TEMPLATE_DIR']:

            if os.path.isdir(self.config['LOCAL_TEMPLATE_DIR']):

                self.jinja_loader = jinja2.ChoiceLoader([
                    jinja2.FileSystemLoader(self.config['LOCAL_TEMPLATE_DIR']),
                    self.jinja_loader,
                ])

                self.logger.info(
                    'site-specific templates will be loaded from: ' +
                    str(self.config['LOCAL_TEMPLATE_DIR']))

            else:
                self.logger.error(
                    'site-specific templates cannot be loaded because LOCAL_TEMPLATE_DIR is not a directory'
                )

        # check for a local static dir, and set up favicon
        if self.config['LOCAL_STATIC_DIR']:
            if os.path.isdir(self.config['LOCAL_STATIC_DIR']):
                self.logger.info(
                    'site-specific static files will be served from: ' +
                    str(self.config['LOCAL_STATIC_DIR']))

                # override the built in / default favicon if one exists
                if os.path.isfile(
                        os.path.join(self.config['LOCAL_STATIC_DIR'],
                                     'favicon.ico')):
                    self.logger.info('site-specific favicon found')
                    self.config['LOCAL_FAVICON'] = True
            else:
                self.config['LOCAL_STATIC_DIR'] = False
                self.logger.error(
                    'site-specific static files cannot be served because LOCAL_STATIC_DIR is not a directory'
                )
Ejemplo n.º 25
0
def create_app(package_name='bidding'):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the korath platform.

    :param package_name: application package name
    :param package_path: application package path
    :param config_name: can have one of [production, development, testing]
    """
    global app, admin
    app = Flask(package_name, instance_relative_config=True)

    config_name = os.environ.get('bidding_CONFIG_NAME', 'Production')

    app.config.from_object('configurations.%s' % config_name.title())

    app.jinja_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader('bidding/templates/'),
    ])

    db.init_app(app)
    admin = Admin(app, 'Our own CMS', base_template='layout.html')

    from . import views
    from views import api_blueprint
    app.register_blueprint(api_blueprint)
    from views import comment_blueprint
    app.register_blueprint(comment_blueprint)
    from views import fb_blueprint
    app.register_blueprint(fb_blueprint)
    from views import static_blueprint
    app.register_blueprint(static_blueprint)

    from . import models

    # for admin panel
    from . import admin_panel
    return app
def load_jupyter_server_extension(nbapp):
    # Add our custom templates to the beginning of the search path.
    templates_dir = pathlib.Path(__file__).parent.absolute().joinpath("templates").as_posix()
    # NbApp settings have already been propogated so we need to modify the webapp settings directly
    # nbapp.extra_template_paths.append(templates_dir)

    env = nbapp.web_app.settings["jinja2_env"]

    if nbapp.__class__.__name__ == 'SingleUserNotebookApp':
        # Running in jupyterhub.

        # jupyterhub-singleuser already extends 'templates/page.html'. Since we
        # want to extend it as well, we have to do something funky here.

        # We are patching this logic:
        # https://github.com/jupyterhub/jupyterhub/blob/9391470e269cf2cbc39520f903ab42900aa991ca/jupyterhub/singleuser.py#L483-L492
        # So that
        # our page.html --extends-> singleuser.page_template --extends-> templates/page.html

        from jupyterhub import singleuser
        import jinja2

        def get_page(name):
            if name == 'singleuser.page_template':
                return singleuser.page_template

        env.loader = jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(os.path.join(templates_dir, 'jupyterhub-singleuser')),
            jinja2.FileSystemLoader(templates_dir),
            jinja2.FunctionLoader(get_page),
            env.loader
        ])

        pass
    else:
        env.loader.searchpath.insert(0, templates_dir)

    nbapp.log.info("Imandra theme enabled!")
Ejemplo n.º 27
0
    def create_app(self, config={}):
        app = Flask('signac-dashboard')
        app.config.update({
            'SECRET_KEY': os.urandom(24),
            'SEND_FILE_MAX_AGE_DEFAULT': 300,  # Cache control for static files
        })

        # Load the provided config
        app.config.update(config)

        # Enable profiling
        if app.config.get('PROFILE'):
            logger.warning("Application profiling is enabled.")
            from werkzeug.contrib.profiler import ProfilerMiddleware
            app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[10])

        # Set up default signac-dashboard static and template paths
        signac_dashboard_path = os.path.dirname(__file__)
        app.static_folder = signac_dashboard_path + '/static'
        app.template_folder = signac_dashboard_path + '/templates'

        # Set up custom template paths
        # The paths in DASHBOARD_PATHS give the preferred order of template
        # loading
        loader_list = []
        for dashpath in list(app.config.get('DASHBOARD_PATHS', [])):
            logger.warning("Adding '{}' to dashboard paths.".format(dashpath))
            loader_list.append(
                jinja2.FileSystemLoader(dashpath + '/templates'))

        # The default loader goes last and is overridden by any custom paths
        loader_list.append(app.jinja_loader)

        app.jinja_loader = jinja2.ChoiceLoader(loader_list)

        turbolinks(app)

        return app
Ejemplo n.º 28
0
def load_devicetype_template(device_type_name, raw=False):
    """
    Loads the bare device-type template as a python dictionary object for
    representation within the device_type templates.
    No device-specific details are parsed - default values only, so some
    parts of the dictionary may be unexpectedly empty. Not to be used when
    rendering device configuration for a testjob.
    :param device_type_name: DeviceType.name (string)
    :param raw: if True, return the raw yaml
    :return: None or a dictionary of the device type template.
    """
    path = os.path.dirname(Device.CONFIG_PATH)
    type_loader = jinja2.FileSystemLoader([os.path.join(path, 'device-types')])
    env = jinja2.Environment(loader=jinja2.ChoiceLoader([type_loader]),
                             trim_blocks=True)
    try:
        template = env.get_template("%s.jinja2" % device_type_name)
        data = template.render()
        if not data:
            return None
        return data if raw else yaml.load(data)
    except (jinja2.TemplateError, yaml.error.YAMLError):
        return None
Ejemplo n.º 29
0
def _init_task_setup_jinja(ctx):
    jinja_env = ctx.jinja_env = _jinja2.Environment(
        loader=_jinja2.ChoiceLoader([
            _jinja2.DictLoader(class_.yaml.get("templates", {}))
            for class_ in reversed(ctx.classes)
        ] + [_jinja2.FileSystemLoader(ctx.inp.path)]),
        keep_trailing_newline=True)

    for k, v in ctx.extras["jinjaglobals"].items():
        jinja_env.globals[k] = v

    for k, v in ctx.extras["jinjafilter"].items():
        jinja_env.filters[k] = v

    for k, v in ctx.extras["jinjatest"].items():
        jinja_env.tests[k] = v

    @_yaql.language.specs.name("template")
    def yaql_template(name, **kw):
        return TemplateResultStr(jinja_env.get_template(name).render(**kw),
                                 name=name)

    ctx.yaql.ctx.register_function(yaql_template)
Ejemplo n.º 30
0
 def register_loaders(self, application=None):
     user_path_loaders = [
         jinja2.FileSystemLoader(path) for path in self.config.get('paths')
     ]
     user_package_loaders = [
         jinja2.PackageLoader(*package)
         for package in self.config.get('packages')
     ]
     user_loaders = user_package_loaders + user_path_loaders
     system_loaders = [
         jinja2.PackageLoader(*package)
         for package in self.config.get('framework_packages')
     ]
     if self._debug_mode:
         loaders = system_loaders + user_loaders
     else:
         loaders = user_loaders + system_loaders
     kwargs = self.config.get('environment', {})
     loader = jinja2.ChoiceLoader(loaders)
     kwargs['loader'] = loader
     self._choice_loader = loader
     self._env = jinja2.Environment(**kwargs)
     self._env.application = application