Ejemplo n.º 1
0
    def __init__(self, settings, loader=FileSystemLoader):
        self.settings = settings

        self.search_path = getattr(settings, 'TEMPLATE_DIRS', list())
        self.loader = import_string(getattr(settings, 'TEMPLATE_LOADER',
                                            'jinja2.FileSystemLoader'))
        if getattr(settings, "JINJA2_BYTECODE_CACHE", False):
            self.bytecode_cache = import_string(getattr(settings, 'JINJA2_BYTECODE_CACHE'))
        else:
            self.bytecode_cache = None

        self.env = Environment(loader=self.loader(self.search_path),
                               auto_reload=getattr(settings, 'JINJA2_AUTO_RELOAD', False),
                               cache_size=getattr(settings, 'JINJA2_CHACHE_SIZE', 50),
                               extensions=getattr(settings, 'JINJA2_EXTENSIONS', ()),
                               bytecode_cache=self.bytecode_cache)
        self.filters = getattr(settings, 'JINJA2_FILTERS', [])
        self.globals = getattr(settings, 'JINJA2_GLOBALS', [])

        # Not good :-(
        for name, f in self.load_filters(self.filters).iteritems():
            self.add_filter(f, name)

        for name, f in self.load_globals(self.globals).iteritems():
            self.add_global(f, name)

        if getattr(settings, 'USE_I18N'):
            try:
                self.env.install_gettext_translations(translation)
            except Exception:
                self.env.install_null_translations()
Ejemplo n.º 2
0
def babel_extract(fileobj, keywords, comment_tags, options):
    """Babel extraction method for Jinja templates.

    .. versionchanged:: 2.3
       Basic support for translation comments was added.  If `comment_tags`
       is now set to a list of keywords for extraction, the extractor will
       try to find the best preceeding comment that begins with one of the
       keywords.  For best results, make sure to not have more than one
       gettext call in one line of code and the matching comment in the
       same line or the line before.

    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a list of keywords (i.e. function names) that should be
                     recognized as translation functions
    :param comment_tags: a list of translator tags to search for and include
                         in the results.
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
             (comments will be empty currently)
    """
    extensions = set()
    for extension in options.get('extensions', '').split(','):
        extension = extension.strip()
        if not extension:
            continue
        extensions.add(import_string(extension))
    if InternationalizationExtension not in extensions:
        extensions.add(InternationalizationExtension)

    environment = get_spontaneous_environment(
        options.get('block_start_string', BLOCK_START_STRING),
        options.get('block_end_string', BLOCK_END_STRING),
        options.get('variable_start_string', VARIABLE_START_STRING),
        options.get('variable_end_string', VARIABLE_END_STRING),
        options.get('comment_start_string', COMMENT_START_STRING),
        options.get('comment_end_string', COMMENT_END_STRING),
        options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
        options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
        str(options.get('trim_blocks', TRIM_BLOCKS)).lower() in \
            ('1', 'on', 'yes', 'true'),
        NEWLINE_SEQUENCE, frozenset(extensions),
        # fill with defaults so that environments are shared
        # with other spontaneus environments.  The rest of the
        # arguments are optimizer, undefined, finalize, autoescape,
        # loader, cache size, auto reloading setting and the
        # bytecode cache
        True, Undefined, None, False, None, 0, False, None
    )

    source = fileobj.read().decode(options.get('encoding', 'utf-8'))
    try:
        node = environment.parse(source)
        tokens = list(environment.lex(environment.preprocess(source)))
    except TemplateSyntaxError as e:
        # skip templates with syntax errors
        return

    finder = _CommentFinder(tokens, comment_tags)
    for lineno, func, message in extract_from_ast(node, keywords):
        yield lineno, func, message, finder.find_comments(lineno)
Ejemplo n.º 3
0
    def visit(self, elem):

        children = [self.visit(child) for child in elem.iterchildren()]

        cls_name = elem.xpath("local-name()")
        ns = elem.nsmap[elem.prefix]
        if ns not in self.imports:
            self.imports[ns] = import_string(ns)
        module = self.imports[ns]
        cls = getattr(module, cls_name)

        wid = elem.attrib.pop("id", None)

        for scls in cls.mro():
            method_name = "visit_{0}".format(scls.__name__)
            method = getattr(self, method_name, None)
            if method:
                result = method(elem, cls, children)
                break
        else:
            result = self.generic_visit(elem, cls, children)

        if wid:
            self.glbls[wid] = result
        return result
Ejemplo n.º 4
0
 def load_extensions(self, extensions):
     """Load extensions
     """
     for extension in extensions:
         if isinstance(extension, basestring):
             extension = import_string(extension)
         self.add_extension(extension)
Ejemplo n.º 5
0
def babel_extract(fileobj, keywords, comment_tags, options):
    extensions = set()
    for extension in options.get('extensions', '').split(','):
        extension = extension.strip()
        if not extension:
            continue
        extensions.add(import_string(extension))

    if InternationalizationExtension not in extensions:
        extensions.add(InternationalizationExtension)

    def getbool(options, key, default = False):
        return options.get(key, str(default)).lower() in ('1', 'on', 'yes', 'true')

    silent = getbool(options, 'silent', True)
    environment = Environment(options.get('block_start_string', BLOCK_START_STRING), options.get('block_end_string', BLOCK_END_STRING), options.get('variable_start_string', VARIABLE_START_STRING), options.get('variable_end_string', VARIABLE_END_STRING), options.get('comment_start_string', COMMENT_START_STRING), options.get('comment_end_string', COMMENT_END_STRING), options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX, options.get('line_comment_prefix') or LINE_COMMENT_PREFIX, getbool(options, 'trim_blocks', TRIM_BLOCKS), NEWLINE_SEQUENCE, frozenset(extensions), cache_size=0, auto_reload=False)
    if getbool(options, 'newstyle_gettext'):
        environment.newstyle_gettext = True
    source = fileobj.read().decode(options.get('encoding', 'utf-8'))
    try:
        node = environment.parse(source)
        tokens = list(environment.lex(environment.preprocess(source)))
    except TemplateSyntaxError as e:
        if not silent:
            raise
        return

    finder = _CommentFinder(tokens, comment_tags)
    for lineno, func, message in extract_from_ast(node, keywords):
        yield (lineno,
         func,
         message,
         finder.find_comments(lineno))
Ejemplo n.º 6
0
def load_extensions(environment, extensions):
    result = {}
    for extension in extensions:
        if isinstance(extension, basestring):
            extension = import_string(extension)
        result[extension.identifier] = extension(environment)

    return result
Ejemplo n.º 7
0
def setup_app(app):
    backend = app.config.get('EMAIL_BACKEND', 'flask.ext.email:ConsoleMail')
    module = import_string(backend)
    backimpl = module()
    backimpl.init_app(app)
    if 'email' not in app.extensions:
        app.extensions['email'] = backimpl
    return app
Ejemplo n.º 8
0
def load_extensions(environment, extensions):
    """Load the extensions from the list and bind it to the environment.
    Returns a dict of instantiated environments.
    """
    result = {}
    for extension in extensions:
        if isinstance(extension, string_types):
            extension = import_string(extension)
        result[extension.identifier] = extension(environment)
    return result
Ejemplo n.º 9
0
def load_extensions(environment, extensions):
    """Load the extensions from the list and bind it to the environment.
    Returns a dict of instantiated environments.
    """
    result = {}
    for extension in extensions:
        if isinstance(extension, string_types):
            extension = import_string(extension)
        result[extension.identifier] = extension(environment)
    return result
Ejemplo n.º 10
0
    def parse(self, parser):
        lineno = next(parser.stream).lineno
        atom_ns = None
        atom_path = []
        atom_args = []
        atom_kwargs = []

        atom_ns = parser.stream.expect('name').value
        parser.stream.expect('colon')

        while parser.stream.current.type not in ['lparen', 'eof']:
            atom_path.append(parser.stream.current.value)
            next(parser.stream)

        parser.stream.expect('lparen')

        while parser.stream.current.type not in ['rparen', 'eof']:
            expr, key = parser.parse_expression(), None
            if parser.stream.skip_if('assign'):
                key = expr
                expr = parser.parse_expression()
            if key:
                atom_kwargs.append(nodes.Keyword(key.name, expr))
            else:
                atom_args.append(expr)
            parser.stream.skip_if('comma')

        parser.stream.expect('rparen')

        env_atoms_ns = self.environment.globals.get('atoms_ns')
        env_atom_host = env_atoms_ns and env_atoms_ns.get(atom_ns)
        if not env_atom_host:
            raise TemplateSyntaxError('"%s" atom namespace not found' % atom_ns, lineno)

        full_atom_path = str('.'.join([env_atom_host, ''.join(atom_path)]))
        env_atom_name = 'loaded_atom_%s' % hashlib.md5(full_atom_path).hexdigest()
        if env_atom_name not in self.environment.globals:
            try:
                imported_atom = import_string(full_atom_path)
            except AttributeError:
                raise ImportError('Atom "%s" not found' % full_atom_path)
            self.environment.globals.update({
                env_atom_name: imported_atom
            })

        atom_func = nodes.Name(env_atom_name, 'load')
        node = nodes.Output([
            nodes.MarkSafeIfAutoescape(
                nodes.Call(atom_func, atom_args, atom_kwargs, None, None)
            )
        ])
        node.set_lineno(lineno)

        return node
Ejemplo n.º 11
0
    def create_env(cls, debug=False, loader=None, **options) -> Environment:
        # bytecode cache
        bytecode_cache = options.pop('bytecode_cache', {})
        bytecode_cache.setdefault('name', 'default')
        bytecode_cache.setdefault('enabled', False)
        bytecode_cache.setdefault(
            'backend', 'aioja.bccache.aiocache.AioRedisBytecodeCache')
        if bytecode_cache['enabled']:
            bytecode_cls = import_string(bytecode_cache['backend'])
            bytecode_options = bytecode_cache.get('options') or {}
            options['bytecode_cache'] = bytecode_cls(**bytecode_options)

        # undefined
        undefined = options.pop('undefined', None)
        if undefined is not None:
            if isinstance(undefined, str):
                options['undefined'] = import_string(undefined)
            else:
                options['undefined'] = undefined

        if debug:
            options.setdefault('undefined', DebugUndefined)
        else:
            options.setdefault('undefined', ChainableUndefined)

        options.setdefault('auto_reload', debug)
        options.setdefault('autoescape', True)

        # environment
        if isinstance(options.get('environment'), str):
            environment_cls = import_string(options.pop('environment'))
        else:
            environment_cls = Environment

        env = environment_cls(loader=loader, **options)

        env.globals.update(DEFAULT_GLOBALS)
        env.filters.update(DEFAULT_FILTERS)
        env.tests.update(DEFAULT_TESTS)
        env.extensions.update(load_extensions(env, DEFAULT_EXTENSIONS))
        return env
Ejemplo n.º 12
0
    def installBlueprint(self, app):
        """
          批量导入蓝图,注册蓝图
              遍历所有的文件夹
              再拼接字符串,利用import_string导入蓝图
              最后再注册蓝图
        """

        for plugin in self.pluginsInfo()['plus_list']:
            if os.path.exists(self.plugins_path + plugin['path'] + '/controller/urls.py'):
                bp = import_string(f'plugins.{plugin["path"]}.controller.urls.blueprint')
                app.register_blueprint(bp, url_prefix=f'/{plugin["apiRoute"]}')
Ejemplo n.º 13
0
def babel_extract(fileobj, keywords, comment_tags, options):
    """Babel extraction method for Jinja templates.

    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a list of keywords (i.e. function names) that should be
                     recognized as translation functions
    :param comment_tags: a list of translator tags to search for and include
                         in the results.  (Unused)
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
             (comments will be empty currently)
    """
    extensions = set()
    for extension in options.get("extensions", "").split(","):
        extension = extension.strip()
        if not extension:
            continue
        extensions.add(import_string(extension))
    if InternationalizationExtension not in extensions:
        extensions.add(InternationalizationExtension)

    environment = get_spontaneous_environment(
        options.get("block_start_string", BLOCK_START_STRING),
        options.get("block_end_string", BLOCK_END_STRING),
        options.get("variable_start_string", VARIABLE_START_STRING),
        options.get("variable_end_string", VARIABLE_END_STRING),
        options.get("comment_start_string", COMMENT_START_STRING),
        options.get("comment_end_string", COMMENT_END_STRING),
        options.get("line_statement_prefix") or LINE_STATEMENT_PREFIX,
        str(options.get("trim_blocks", TRIM_BLOCKS)).lower() in ("1", "on", "yes", "true"),
        NEWLINE_SEQUENCE,
        frozenset(extensions),
        # fill with defaults so that environments are shared
        # with other spontaneus environments.  The rest of the
        # arguments are optimizer, undefined, finalize, autoescape,
        # loader, cache size, auto reloading setting and the
        # bytecode cache
        True,
        Undefined,
        None,
        False,
        None,
        0,
        False,
        None,
    )

    source = fileobj.read().decode(options.get("encoding", "utf-8"))
    try:
        node = environment.parse(source)
    except TemplateSyntaxError, e:
        # skip templates with syntax errors
        return
Ejemplo n.º 14
0
    def extend(self, *args, scope_: Scope = Scope.GLOBALS, **kwargs):
        """
        Add extra filters, tests, globals or policies.
        This method accepts the same arguments as the `dict` constructor:
        A dict, a dict subclass or some keyword arguments.
        """
        extensions = dict(*args, **kwargs)

        target = getattr(self.env, scope_.value)
        for name, ext in extensions.items():
            if isinstance(ext, str):
                ext = import_string(ext)
            target[name] = ext
Ejemplo n.º 15
0
def main(global_config, **settings):
    """ This function returns the Pyramid WSGI application.
    """
    config = Configurator(settings=settings)

    # http://docs.pylonsproject.org/projects/pyramid_exclog/dev/api.html#pyramid_exclog.includeme
    config.include('pyramid_exclog')
    # https://docs.pylonsproject.org/projects/pyramid_jinja2/dev/api.html#pyramid_jinja2.includeme
    config.include('pyramid_jinja2')
    config.get_jinja2_environment().filters.update({
        'date_format' : import_string('tumblrproxy.lib.template_filter.date_format'),
        'tumblr_video' : import_string('tumblrproxy.lib.tumblr_filter.video_embed')
    })

    # view handler
    config.include('tumblrproxy.controllers.blog')

    # jinja2 configuration
    config.add_jinja2_search_path("tumblrproxy:templates")

    # static content route
    config.add_static_view('static', 'static', cache_max_age=3600)

    return config.make_wsgi_app()
Ejemplo n.º 16
0
    def install_blueprint(self, app):
        """
          批量导入蓝图,注册蓝图
              遍历所有的文件夹
              再拼接字符串,利用import_string导入蓝图
              最后再注册蓝图
        """

        for plugin in self.plugins_info()['plus_list']:
            # 加载目录
            plugin_path_dir_list = [i for i in os.listdir(self.plugins_path + plugin['path']) if "." not in i]
            for plugin_path_dir in plugin_path_dir_list:
                if os.path.exists(self.plugins_path + plugin['path'] + f'/{plugin_path_dir}/urls.py'):
                    bp = import_string(f'plugins.{plugin["path"]}.{plugin_path_dir}.urls.blueprint')
                    app.register_blueprint(bp, url_prefix=f'{bp.name}')
Ejemplo n.º 17
0
def babel_extract(fileobj, keywords, comment_tags, options):
    """Babel extraction method for Jinja templates.

    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a list of keywords (i.e. function names) that should be
                     recognized as translation functions
    :param comment_tags: a list of translator tags to search for and include
                         in the results.  (Unused)
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
             (comments will be empty currently)
    """
    extensions = set()
    for extension in options.get('extensions', '').split(','):
        extension = extension.strip()
        if not extension:
            continue
        extensions.add(import_string(extension))
    if InternationalizationExtension not in extensions:
        extensions.add(InternationalizationExtension)

    environment = get_spontaneous_environment(
        options.get('block_start_string', BLOCK_START_STRING),
        options.get('block_end_string', BLOCK_END_STRING),
        options.get('variable_start_string', VARIABLE_START_STRING),
        options.get('variable_end_string', VARIABLE_END_STRING),
        options.get('comment_start_string', COMMENT_START_STRING),
        options.get('comment_end_string', COMMENT_END_STRING),
        options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
        options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
        str(options.get('trim_blocks', TRIM_BLOCKS)).lower() in \
            ('1', 'on', 'yes', 'true'),
        NEWLINE_SEQUENCE, frozenset(extensions),
        # fill with defaults so that environments are shared
        # with other spontaneus environments.  The rest of the
        # arguments are optimizer, undefined, finalize, autoescape,
        # loader, cache size, auto reloading setting and the
        # bytecode cache
        True, Undefined, None, False, None, 0, False, None
    )

    source = fileobj.read().decode(options.get('encoding', 'utf-8'))
    try:
        node = environment.parse(source)
    except TemplateSyntaxError, e:
        # skip templates with syntax errors
        return
Ejemplo n.º 18
0
def create_app(mode):
    app = Flask(__name__)

    bp = import_string(blueprint)
    app.register_blueprint(bp)

    register_errors(app)

    app.config['SQLALCHEMY_DATABASE_URI'] = config[
        mode].SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = config[
        mode].SQLALCHEMY_TRACK_MODIFICATIONS
    app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = config[
        mode].SQLALCHEMY_COMMIT_ON_TEARDOWN
    db.init_app(app=app)

    return app
Ejemplo n.º 19
0
async def index(request):
    settings = Settings()

    if request.method == METH_POST:
        # the 302 redirect is processed as an exception, so if this coroutine returns there's a form error
        form_errors = await process_form(request)
    else:
        form_errors = None

    network_klass = import_string(settings.NETWORK_CLASS)
    network_api = network_klass()
    network_status = network_api.status()

    return {
        'page_title': 'Network',
        'network_status': network_status,
        'form_errors': form_errors
    }
Ejemplo n.º 20
0
def babel_extract(fileobj, keywords, comment_tags, options):
    extensions = set()
    for extension in options.get('extensions', '').split(','):
        extension = extension.strip()
        if not extension:
            continue
        extensions.add(import_string(extension))

    if InternationalizationExtension not in extensions:
        extensions.add(InternationalizationExtension)

    def getbool(options, key, default=False):
        return options.get(key,
                           str(default)).lower() in ('1', 'on', 'yes', 'true')

    silent = getbool(options, 'silent', True)
    environment = Environment(
        options.get('block_start_string', BLOCK_START_STRING),
        options.get('block_end_string', BLOCK_END_STRING),
        options.get('variable_start_string', VARIABLE_START_STRING),
        options.get('variable_end_string', VARIABLE_END_STRING),
        options.get('comment_start_string', COMMENT_START_STRING),
        options.get('comment_end_string', COMMENT_END_STRING),
        options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
        options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
        getbool(options, 'trim_blocks', TRIM_BLOCKS),
        NEWLINE_SEQUENCE,
        frozenset(extensions),
        cache_size=0,
        auto_reload=False)
    if getbool(options, 'newstyle_gettext'):
        environment.newstyle_gettext = True
    source = fileobj.read().decode(options.get('encoding', 'utf-8'))
    try:
        node = environment.parse(source)
        tokens = list(environment.lex(environment.preprocess(source)))
    except TemplateSyntaxError as e:
        if not silent:
            raise
        return

    finder = _CommentFinder(tokens, comment_tags)
    for lineno, func, message in extract_from_ast(node, keywords):
        yield (lineno, func, message, finder.find_comments(lineno))
Ejemplo n.º 21
0
def routes_info():
    """
    Available API description
    """
    routes = []
    for rule in app.url_map.iter_rules():
        try:
            if rule.endpoint != 'static':
                if hasattr(app.view_functions[rule.endpoint], 'import_name'):
                    import_name = app.view_functions[rule.endpoint].import_name
                    obj = import_string(import_name)
                    routes.append({
                        rule.rule:
                        "%s\n%s" % (",".join(list(rule.methods)), obj.__doc__)
                    })
                else:
                    methods = list(
                        filter(
                            lambda x: x in
                            ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'],
                            list(rule.methods)))

                    methods_repr = []
                    for m in methods:
                        methods_repr.append(m)

                    endpoint_doc = app.view_functions[rule.endpoint].__doc__
                    if endpoint_doc:
                        methods_repr.append(
                            list(str(endpoint_doc).split('\n'))[1:-1])

                    routes.append({rule.rule: methods_repr})
        except Exception as exc:
            routes.append({
                rule.rule:
                "(%s) INVALID ROUTE DEFINITION!!!" % rule.endpoint
            })
            route_info = "%s => %s" % (rule.rule, rule.endpoint)
            app.logger.error("Invalid route: %s" % route_info, exc_info=True)

    routes = sorted(routes, key=lambda d: list(d.keys()))
    return jsonify(code=200, data=routes)
Ejemplo n.º 22
0
async def process_form(request):
    settings = Settings()

    new_job = {}
    missing_fields = []

    fields = ['ontology_id', 'json_content']

    data = await request.post()
    for f in fields:
        new_job[f] = data.get(f)
        if not new_job[f]:
            missing_fields.append(f)

    if missing_fields:
        return 'Invalid form submission, missing fields: {}'.format(
            ', '.join(missing_fields))

    ontology_id = new_job['ontology_id']
    json_content = loads(new_job['json_content'])

    session = await get_session(request)
    session['ontology_id'] = ontology_id

    service_klass = import_string(settings.SERVICE_CLASS)

    agent_id = service_klass().find_provider(ontology_id)

    if not service_klass.can_perform(agent_id, ontology_id):
        return 'The service indicates that this service cannot be performed at this time'

    result = service_klass.perform(agent_id, ontology_id, json_content)

    # TODO Record the result of the perform so we can check on its status

    redirect_url = request.app.router['jobs'].url()

    raise HTTPFound(redirect_url)
Ejemplo n.º 23
0
def generator_router(dir_name, module_join):
    """
    自动导入路由
    :return:
    """
    for name in os.listdir(dir_name):
        file_name = os.path.join(dir_name, name)
        if os.path.isfile(file_name):
            if (name.endswith('.py') and not name.endswith('not_import.py')
                    and not name.endswith('router.py')
                    and not name.endswith('route.py')
                    and name != '__init__.py'):
                module_name = name[:name.rfind('.')]
                module_path = module_join + '.' + module_name
                module = import_string(module_path)
                for child in dir(module):
                    if child not in names:
                        child_module = getattr(module, child)
                        if ischildof(child_module, Resource):
                            child_module_name = module_path + '.' + child
                            if child_module_name not in view_set:
                                view_set.add(child_module_name)
                                try:
                                    if isinstance(child_module.api_url,
                                                  basestring):
                                        api.add_resource(
                                            child_module, child_module.api_url)
                                    else:
                                        api.add_resource(
                                            child_module,
                                            *child_module.api_url)
                                except AssertionError:
                                    print('has: ' + child_module_name)

        elif name != '__pycache__':
            # pass
            generator_router(file_name, module_join + '.' + name)
Ejemplo n.º 24
0
def help():
    """Print all defined routes and their endpoint docstrings

    This also handles flask-router, which uses a centralized scheme
    to deal with routes, instead of defining them as a decorator
    on the target function.
    """
    routes = []
    for rule in flask.current_app.url_map.iter_rules():
        try:
            if rule.endpoint != 'static':
                if hasattr(flask.current_app.view_functions[rule.endpoint],
                           'import_name'):
                    import_name = flask.current_app.view_functions[
                        rule.endpoint].import_name
                    obj = import_string(import_name)
                    routes.append({
                        rule.rule:
                        "%s\n%s" % (",".join(list(rule.methods)), obj.__doc__)
                    })
                else:
                    routes.append({
                        rule.rule:
                        flask.current_app.view_functions[rule.endpoint].__doc__
                    })
        except Exception as exc:
            routes.append({
                rule.rule:
                "(%s) INVALID ROUTE DEFINITION!!!" % rule.endpoint
            })
            route_info = "%s => %s" % (rule.rule, rule.endpoint)
            flask.current_app.logger.error("Invalid route: %s" % route_info,
                                           exc_info=True)
            # func_list[rule.rule] = obj.__doc__

    return flask.jsonify(code=200, data=routes)
Ejemplo n.º 25
0
def maybe_import_string(val):
    if isinstance(val, string_types):
        return import_string(val.strip())
    return val
Ejemplo n.º 26
0
def babel_extract(fileobj, keywords, comment_tags, options):
    """Babel extraction method for Jinja templates.

    .. versionchanged:: 2.3
       Basic support for translation comments was added.  If `comment_tags`
       is now set to a list of keywords for extraction, the extractor will
       try to find the best preceeding comment that begins with one of the
       keywords.  For best results, make sure to not have more than one
       gettext call in one line of code and the matching comment in the
       same line or the line before.

    .. versionchanged:: 2.5.1
       The `newstyle_gettext` flag can be set to `True` to enable newstyle
       gettext calls.

    .. versionchanged:: 2.7
       A `silent` option can now be provided.  If set to `False` template
       syntax errors are propagated instead of being ignored.

    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a list of keywords (i.e. function names) that should be
                     recognized as translation functions
    :param comment_tags: a list of translator tags to search for and include
                         in the results.
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
             (comments will be empty currently)
    """
    extensions = set()
    for extension in options.get('extensions', '').split(','):
        extension = extension.strip()
        if not extension:
            continue
        extensions.add(import_string(extension))
    if InternationalizationExtension not in extensions:
        extensions.add(InternationalizationExtension)

    def getbool(options, key, default=False):
        return options.get(key, str(default)).lower() in \
            ('1', 'on', 'yes', 'true')

    silent = getbool(options, 'silent', True)
    environment = Environment(
        options.get('block_start_string', BLOCK_START_STRING),
        options.get('block_end_string', BLOCK_END_STRING),
        options.get('variable_start_string', VARIABLE_START_STRING),
        options.get('variable_end_string', VARIABLE_END_STRING),
        options.get('comment_start_string', COMMENT_START_STRING),
        options.get('comment_end_string', COMMENT_END_STRING),
        options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
        options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
        getbool(options, 'trim_blocks', TRIM_BLOCKS),
        getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),
        NEWLINE_SEQUENCE,
        getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),
        frozenset(extensions),
        cache_size=0,
        auto_reload=False
    )

    if getbool(options, 'newstyle_gettext'):
        environment.newstyle_gettext = True

    source = fileobj.read().decode(options.get('encoding', 'utf-8'))
    try:
        node = environment.parse(source)
        tokens = list(environment.lex(environment.preprocess(source)))
    except TemplateSyntaxError as e:
        if not silent:
            raise
        # skip templates with syntax errors
        return

    finder = _CommentFinder(tokens, comment_tags)
    for lineno, func, message in extract_from_ast(node, keywords):
        yield lineno, func, message, finder.find_comments(lineno)
Ejemplo n.º 27
0
def maybe_import_string(val):
    if isinstance(val, basestring):
        return import_string(val.strip())
    return val
Ejemplo n.º 28
0
"""Base application, run this to start the backend."""
import os
from flask import Flask
from jinja2.utils import import_string
from src import auth, generate_sudoku, static, score_boards
from src.models import DB

APP = Flask(__name__)
try:
    if os.environ['ENV'] == 'prod':
        APP.config.from_object(import_string('config.ProductionConfig'))
    elif os.environ['ENV'] == "test":
        APP.config.from_object(import_string('config.TestingConfig'))
    elif os.environ['ENV'] == "staging":
        APP.config.from_object(import_string('config.StagingConfig'))
    else:
        APP.config.from_object(import_string('config.DevelopmentConfig'))
except KeyError:
    APP.config.from_object(import_string('config.DevelopmentConfig'))

APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

APP.register_blueprint(auth.BP)

APP.register_blueprint(generate_sudoku.BP)

APP.register_blueprint(score_boards.BP)

APP.register_blueprint(static.BP)

DB.init_app(APP)
Ejemplo n.º 29
0
        print('No previous compressed files found in {output_dir}'
              .format(output_dir=env.compressor_output_dir))

    template_dirs = [os.path.join(app.root_path, x)
                     for x in get_template_dirs(app)]

    print('Compressing static assets into {output_dir}'
          .format(output_dir=env.compressor_output_dir))
    compressor = env.extensions['jac.extension.CompressorExtension'].compressor
    compressor.offline_compress(env, template_dirs)

    print('Finished offline-compressing static assets.')
    return 0


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('You have to specify the app i.e. my_module:create_app or my_module:app', file=sys.stderr)
        exit(1)

    try:
        from flask import Flask
    except ImportError:
        print('Make sure you have flask installed to run this script\n\n', file=sys.stderr)
        raise

    app_factory = import_string(sys.argv[1])
    app = app_factory() if callable(app_factory) and not isinstance(app_factory, Flask) else app_factory
    with app.app_context():
        sys.exit(offline_compile(app))
Ejemplo n.º 30
0
def maybe_import_string(val):
    if isinstance(val, basestring):
        return import_string(val.strip())
    return val
Ejemplo n.º 31
0
 def __init__(self, params):
     self.context_processors = [
         import_string(p)
         for p in params['OPTIONS'].pop('context_processors', [])
     ]
     super(Jinja2Backend, self).__init__(params)
Ejemplo n.º 32
0
def has_attr(obj_path: str, attr: str) -> bool:
    # https://jinja.palletsprojects.com/en/3.0.x/api/#custom-tests
    obj = import_string(obj_path)
    return hasattr(obj, attr)
Ejemplo n.º 33
0
        os.path.join(app.root_path, x) for x in get_template_dirs(app)
    ]

    print('Compressing static assets into {output_dir}'.format(
        output_dir=env.compressor_output_dir))
    compressor = env.extensions['jac.extension.CompressorExtension'].compressor
    compressor.offline_compress(env, template_dirs)

    print('Finished offline-compressing static assets.')
    return 0


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print(
            'You have to specify the app i.e. my_module:create_app or my_module:app',
            file=sys.stderr)
        exit(1)

    try:
        from flask import Flask
    except ImportError:
        print('Make sure you have flask installed to run this script\n\n',
              file=sys.stderr)
        raise

    app_factory = import_string(sys.argv[1])
    app = app_factory() if callable(app_factory) and not isinstance(
        app_factory, Flask) else app_factory
    sys.exit(offline_compile(app))