示例#1
0
def nb_renderer(full_path):
    directory, base = split(full_path)
    cache_file = join(directory, '.%s.html' % base)
    if not current_app.config.get('DEBUG'):
        try:
            if isfile(cache_file) and getmtime(full_path) < getmtime(cache_file):
                current_app.logger.debug('Using Cache File %s' % cache_file)
                return raw_renderer(cache_file)
        except:
            current_app.logger.warn('There was an error reading from the cache file %s' % cache_file)

    ex = HTMLExporter(extra_loaders=[current_app.jinja_env.loader],
                      template_file='wakari_notebook.html')

    ex.environment.globals.update(current_app.jinja_env.globals)
    current_app.update_template_context(ex.environment.globals)
    ex.environment.globals.update(dirname=dirname(request.view_args['path']))

    output, _ = ex.from_filename(full_path)


    try:
        with open(cache_file, 'w') as fd:
            current_app.logger.debug('Writing Cache File %s' % cache_file)
            fd.write(output.encode(errors='replace'))
    except (OSError, IOError):
        current_app.logger.warn('There was an error writing to the cache file %s' % cache_file)
        try:
            if isfile(cache_file): os.unlink(cache_file)
        except OSError:
            current_app.logger.warn('There was an error removing the cache file %s' % cache_file)
            pass

    return output
示例#2
0
def stream_template(template_name, **context):
    # http://stackoverflow.com/questions/13386681/streaming-data-with-python-and-flask
    # http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates
    current_app.update_template_context(context)
    t = current_app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    return rv
示例#3
0
def get_template_module(template_name, **context):
    """Returns the python module of a template.

    This allows you to call e.g. macros inside it from Python code."""
    app.update_template_context(context)
    tpl = app.jinja_env.get_template(template_name)
    return tpl.make_module(context)
示例#4
0
def get_template_module(template_name_or_list, **context):
    """Returns the python module of a template.

    This allows you to call e.g. macros inside it from Python code."""
    current_app.update_template_context(context)
    tpl = current_app.jinja_env.get_or_select_template(template_name_or_list)
    return tpl.make_module(context)
示例#5
0
def get_template_module(template_name_or_list, **context):
    """Returns the python module of a template.

    This allows you to call e.g. macros inside it from Python code."""
    current_app.update_template_context(context)
    tpl = current_app.jinja_env.get_or_select_template(template_name_or_list)
    return tpl.make_module(context)
示例#6
0
def stream_template(template_name, **context):
    # http://stackoverflow.com/questions/13386681/streaming-data-with-python-and-flask
    # http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates
    current_app.update_template_context(context)
    t = current_app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    return rv
示例#7
0
def get_template_module(template_name, **context):
    """Returns the python module of a template.

    This allows you to call e.g. macros inside it from Python code."""
    app.update_template_context(context)
    tpl = app.jinja_env.get_template(template_name)
    return tpl.make_module(context)
示例#8
0
	def __call__(self, c, params):
		"""\
			Run this template.
			"""
		current_app.update_template_context(params)
		c.content = self.template.render(**params)
		c.from_mime = self.db_template.adapter.to_mime
		return c.content
示例#9
0
    def __call__(self, c, params):
        """\
			Run this template.
			"""
        current_app.update_template_context(params)
        c.content = self.template.render(**params)
        c.from_mime = self.db_template.adapter.to_mime
        return c.content
def stream_template(template_name, **context):
    # http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates
    app.update_template_context(context)
    t = app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    # uncomment if you don't need immediate reaction
    ##rv.enable_buffering(5)
    return rv
示例#11
0
def stream_template(template_name, **context):
    """ Stream a template

    Needs to be used with Response(stream_template(...))
    """
    current_app.update_template_context(context)
    t = current_app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    rv.enable_buffering(5)
    return rv
示例#12
0
def render_square_bracket_template(template_name, context):
  env = current_app.jinja_env.overlay(block_start_string = "[%",
                                      block_end_string = "%]",
                                      variable_start_string = "[[",
                                      variable_end_string = "]]",
                                      comment_start_string = "[#",
                                      comment_end_string = "#]")
  current_app.update_template_context(context)
  template = env.get_template(template_name)
  return template.render(**context)
        def stream_template(template_name, **context):
            """
            The jinja2 template supports rendering templates piece by piece,
            however the request context is not kept during whole time of
            template rendering process.

            @ see: http://flask.pocoo.org/docs/patterns/streaming/
            """
            current_app.update_template_context(context)
            t = current_app.jinja_env.get_template(template_name)
            rv = t.stream(context)

            return stream_with_context(rv)
示例#14
0
def generate_template(template=None,
                      context=None,
                      method=None,
                      string=None,
                      filter=None):
    """Creates a Genshi template stream that you can
    run filters and transformations on.

    """
    genshi = current_app.extensions['genshi']
    method = genshi._method_for(template, method)
    class_ = genshi.methods[method].get('class', MarkupTemplate)

    context = context or {}
    for key, value in list(current_app.jinja_env.globals.items()):
        context.setdefault(key, value)
    context.setdefault('filters', current_app.jinja_env.filters)
    context.setdefault('tests', current_app.jinja_env.tests)
    for key, value in list(current_app.jinja_env.filters.items()):
        context.setdefault(key, value)
    for key, value in list(current_app.jinja_env.tests.items()):
        context.setdefault('is%s' % key, value)
    current_app.update_template_context(context)

    if template is not None:
        template = genshi.template_loader.load(template, cls=class_)
    elif string is not None:
        template = class_(string)
    else:
        raise RuntimeError('Need a template or string')

    stream = template.generate(**context)

    if signals_available:
        template_generated.send(current_app._get_current_object(),
                                template=template,
                                context=context)

    for func in genshi.filters[method]:
        if len(getargspec(func)[0]) == 2:  # Filter takes context?
            stream = func(stream, context)
        else:
            stream = func(stream)

    if filter:
        if len(getargspec(filter)[0]) == 2:  # Filter takes context?
            stream = list(filter(stream, context))
        else:
            stream = list(filter(stream))

    return stream
示例#15
0
    def stream_template(template_name, **context):
        """
        The jinja2 template supports rendering templates piece by piece,
        however the request context is not kept during whole time of
        template rendering process.

        see::
            http://flask.pocoo.org/docs/patterns/streaming/
        """
        current_app.update_template_context(context)
        t = current_app.jinja_env.get_template(template_name)
        rv = t.stream(context)

        return stream_with_context(rv)
示例#16
0
def render(template_name, request, status_code=None, **template_vars):
    template_vars['request'] = request
    template_vars['session'] = session
    template_vars['config'] = current_app.config
    current_app.update_template_context(template_vars)
    body = renderer.render(template_name, **template_vars)

    if status_code is None:
        if request.method == 'POST':
            status_code = 201
        elif request.method == 'DELETE':
            status_code = 204
        else:
            status_code = 200

    return Response(body, status=status_code)
示例#17
0
def render(template_name, request, status_code=None, **template_vars):
    template_vars["request"] = request
    template_vars["session"] = session
    template_vars["config"] = current_app.config
    current_app.update_template_context(template_vars)
    body = renderer.render(template_name, **template_vars)

    if status_code is None:
        if request.method == "POST":
            status_code = 201
        elif request.method == "DELETE":
            status_code = 204
        else:
            status_code = 200

    return Response(body, status=status_code)
示例#18
0
def generate_template(template=None, context=None,
                      method=None, string=None, filter=None):
    """Creates a Genshi template stream that you can
    run filters and transformations on.

    """
    genshi = current_app.extensions['genshi']
    method = genshi._method_for(template, method)
    class_ = genshi.methods[method].get('class', MarkupTemplate)

    context = context or {}
    for key, value in current_app.jinja_env.globals.iteritems():
        context.setdefault(key, value)
    context.setdefault('filters', current_app.jinja_env.filters)
    context.setdefault('tests', current_app.jinja_env.tests)
    for key, value in current_app.jinja_env.filters.iteritems():
        context.setdefault(key, value)
    for key, value in current_app.jinja_env.tests.iteritems():
        context.setdefault('is%s' % key, value)
    current_app.update_template_context(context)

    if template is not None:
        template = genshi.template_loader.load(template, cls=class_)
    elif string is not None:
        template = class_(string)
    else:
        raise RuntimeError('Need a template or string')

    stream = template.generate(**context)

    if signals_available:
        template_generated.send(current_app._get_current_object(),
                                template=template, context=context)

    for func in genshi.filters[method]:
        if len(getargspec(func)[0]) == 2:  # Filter takes context?
            stream = func(stream, context)
        else:
            stream = func(stream)

    if filter:
        if len(getargspec(filter)[0]) == 2:  # Filter takes context?
            stream = filter(stream, context)
        else:
            stream = filter(stream)

    return stream
示例#19
0
def experiment_dashboard(exp_uid, app_id):
    """
    Endpoint that renders the experiment dashboard.

    Inputs: ::\n
    	(string) exp_uid, exp_uid for a current experiment.
    """

    simple_flag = int(request.args.get('simple', 0))
    force_recompute = int(request.args.get('force_recompute', 1))

    if rm.get_experiment(exp_uid) is None:
        return render_template('exp_404.html', exp_uid=exp_uid), 404

    # Not a particularly good way to do this.
    alg_label_list = rm.get_algs_for_exp_uid(exp_uid)
    alg_list = [{
        'alg_label': alg['alg_label'],
        'alg_label_clean': '_'.join(alg['alg_label'].split())
    } for alg in alg_label_list]

    # -- Directly use Jinja2 to load and render the app-specific dashboard template.
    env = Environment(loader=ChoiceLoader([
        PackageLoader('apps.{}'.format(app_id), 'dashboard'),
        PackageLoader('next.dashboard', 'templates')
    ]))
    template = env.get_template(
        'myAppDashboard.html'.format(app_id)
    )  # looks for /next/apps/{{ app_id }}/dashboard/{{ app_id }}.html
    # The context we pass to the dashboard template.
    ctx = dict(
        app_id=app_id,
        exp_uid=exp_uid,
        alg_list=alg_list,
        exceptions_present=False,  #exceptions_present(exp_uid),
        url_for=url_for,
        simple_flag=int(simple_flag),
        force_recompute=int(force_recompute))
    # Inject standard Flask context + context processors
    current_app.update_template_context(ctx)

    # Render the template
    return template.render(**ctx)
示例#20
0
def generate_template(template=None, context=None, method=None, string=None):
    """Creates a Kajiki template stream that you can
    run filters and transformations on.

    """
    kajiki = current_app.extensions['kajiki']
    method = kajiki._method_for(template, method)
    class_ = kajiki.methods[method].get('class', XMLTemplate)

    filters = current_app.jinja_env.filters.copy()
    for name, f in filters.items():
        if getattr(f, 'environmentfilter', False):
            filters[name] = (lambda f: lambda *args, **kw: f(
                current_app.jinja_env, *args, **kw))(f)
        elif getattr(f, 'contextfilter', False):
            filters[name] = (lambda f: lambda *args, **kw: f(
                FakeJinjaContext(current_app.jinja_env), *args, **kw))(f)
        elif getattr(f, 'evalcontextfilter', False):
            filters[name] = (lambda f: lambda *args, **kw: f(
                FakeJinjaEvalContext(current_app.jinja_env), *args, **kw))(f)

    context = context or {}
    for key, value in current_app.jinja_env.globals.items():
        context.setdefault(key, value)
    context.setdefault('filters', filters)
    context.setdefault('tests', current_app.jinja_env.tests)
    for key, value in filters.items():
        context.setdefault(key, value)
    for key, value in current_app.jinja_env.tests.items():
        context.setdefault('is%s' % key, value)
    current_app.update_template_context(context)

    if template is not None:
        # TODO cls=class_
        template = kajiki.template_loader.load(template)
    elif string is not None:
        template = class_(string)
    else:
        raise RuntimeError('Need a template or string')

    return template(context)
示例#21
0
def generate_template(template=None, context=None,
                      method=None, string=None, filter=None):
    """Creates a Genshi template stream that you can
    run filters and transformations on.

    """
    genshi = current_app.extensions['genshi']
    method = genshi._method_for(template, method)
    class_ = genshi.methods[method].get('class', MarkupTemplate)

    filters = current_app.jinja_env.filters.copy()
    for name, f in filters.items():
        if getattr(f, "environmentfilter", False):
            filters[name] = (
                lambda f: lambda *args, **kw: f(current_app.jinja_env, *args, **kw)
            )(f)
        elif getattr(f, "contextfilter", False):
            filters[name] = (
                lambda f: lambda *args, **kw: f(
                    FakeJinjaContext(current_app.jinja_env), *args, **kw
                )
            )(f)
        elif getattr(f, "evalcontextfilter", False):
            filters[name] = (
                lambda f: lambda *args, **kw: f(
                    FakeJinjaEvalContext(current_app.jinja_env), *args, **kw
                )
            )(f)

    context = context or {}
    for key, value in current_app.jinja_env.globals.items():
        context.setdefault(key, value)
    context.setdefault('filters', filters)
    context.setdefault('tests', current_app.jinja_env.tests)
    current_app.update_template_context(context)

    if template is not None:
        template = genshi.template_loader.load(template, cls=class_)
    elif string is not None:
        template = class_(string)
    else:
        raise RuntimeError('Need a template or string')

    stream = template.generate(**context)

    if signals_available:
        template_generated.send(current_app._get_current_object(),
                                template=template, context=context)

    for func in genshi.filters[method]:
        if len(getfullargspec(func)[0]) == 2:  # Filter takes context?
            stream = func(stream, context)
        else:
            stream = func(stream)

    if filter:
        if len(getfullargspec(filter)[0]) == 2:  # Filter takes context?
            stream = filter(stream, context)
        else:
            stream = filter(stream)

    return stream
示例#22
0
    def search_to_context(self,
                          lookup_value,
                          detailed=False,
                          **default_context_kwargs):
        """ This needs a big redo.

            Note however: new-style templates require similar input
            across Detail/main page view, so can really refactor and
            chop stuff down.

            TODO: inclusion of context_processors ?

            TODO: And the big mess is:
              * do_search_to_obj
              * search_context - simplify
        """

        current_pair, _ = current_app.config.resolve_original_pair(
            g._from, g._to)
        async_paradigm = current_pair.get('asynchronous_paradigms', False)

        lemma_attrs = default_context_kwargs.get('lemma_attrs', {})

        if detailed and not async_paradigm:
            generate = True
        else:
            generate = False

        if 'variant_type' in default_context_kwargs:
            variant_type = default_context_kwargs.get('variant_type')
            search_result_obj = self.do_search_to_obj(
                lookup_value,
                generate=generate,
                lemma_attrs=lemma_attrs,
                variant_type=variant_type)
        else:
            search_result_obj = self.do_search_to_obj(lookup_value,
                                                      generate=generate,
                                                      lemma_attrs=lemma_attrs)

        if detailed:
            template = 'detail_entry.template'
        else:
            template = 'entry.template'

        _rendered_entry_templates = []

        template_results = [{
            'input':
            search_result_obj.search_term,
            'lookups':
            search_result_obj.formatted_results_sorted
        }]

        logIndexLookups(search_result_obj.search_term, template_results,
                        g._from, g._to)

        show_info = False

        def sort_entry(r):
            if r[0] is None:
                return False
            if len(r[0]) > 0:
                return False
            try:
                return ''.join(r[0].xpath('./lg/l/text()'))
            except:
                return False

        # TODO: sorting_problem
        for lz, az, paradigm, has_layout in search_result_obj.entries_and_tags_and_paradigms:
            if lz is not None:
                user_input = search_result_obj.search_term
                candidate_word_forms = determine_recording_word_forms(
                    user_input, paradigm)
                tplkwargs = {
                    'lexicon_entry':
                    lz,
                    'analyses':
                    az,
                    'recording_word_forms':
                    candidate_word_forms,
                    'paradigm':
                    paradigm,
                    'layout':
                    has_layout,
                    'user_input':
                    user_input,
                    'word_searches':
                    template_results,
                    'errors':
                    False,
                    'show_info':
                    show_info,
                    'successful_entry_exists':
                    search_result_obj.successful_entry_exists
                }

                tplkwargs.update(**default_context_kwargs)

                # Process all the context processors
                current_app.update_template_context(tplkwargs)

                _rendered_entry_templates.append(
                    current_app.lexicon_templates.render_template(
                        g._from, template, **tplkwargs))

        all_az = sum([
            az for _, az in sorted(search_result_obj.entries_and_tags,
                                   key=sort_entry)
        ], [])

        indiv_template_kwargs = {
            'analyses': all_az,
            'recordings_endpoint': current_app.config.recordings_endpoint
        }
        indiv_template_kwargs.update(**default_context_kwargs)

        # Process all the context processors
        current_app.update_template_context(indiv_template_kwargs)

        all_analysis_template = \
            current_app.lexicon_templates.render_individual_template(g._from, 'analyses.template', **indiv_template_kwargs)

        header_template = \
            current_app.lexicon_templates.render_individual_template(g._from, 'includes.template', **indiv_template_kwargs)

        if search_result_obj.analyses_without_lex:
            leftover_tpl_kwargs = {
                'analyses': search_result_obj.analyses_without_lex,
            }
            leftover_tpl_kwargs.update(**default_context_kwargs)
            # Process all the context processors
            current_app.update_template_context(leftover_tpl_kwargs)

            leftover_analyses_template = \
                current_app.lexicon_templates.render_individual_template( g._from
                                                                        , 'analyses.template'
                                                                        , **leftover_tpl_kwargs
                                                                        )
        else:
            leftover_analyses_template = False

        search_context = {

            # This is the new style stuff.
            'entry_templates':
            _rendered_entry_templates,
            'entry_template_header_includes':
            header_template,
            'leftover_analyses_template':
            leftover_analyses_template,
            'all_analysis_template':
            all_analysis_template,

            # These variables can be turned into something more general
            'successful_entry_exists':
            search_result_obj.successful_entry_exists,
            'word_searches':
            template_results,
            'analyses':
            search_result_obj.analyses,
            'analyses_without_lex':
            search_result_obj.analyses_without_lex,
            'user_input':
            search_result_obj.search_term,
            'last_searches':
            session.get('last_searches-' + current_app.config.short_name, []),

            # ?
            'errors':
            False,  # where should we expect errors?
            'language_pairs_other_results':
            search_result_obj.other_results,
            'debug_text':
            search_result_obj.debug_text
        }

        search_context.update(**default_context_kwargs)

        return self.post_search_context_modification(search_result_obj,
                                                     search_context)
示例#23
0
 def stream_template(template_name, **context):
     current_app.update_template_context(context)
     template = current_app.jinja_env.get_template(template_name)
     stream = template.stream(context)
     stream.enable_buffering(10)
     return stream
示例#24
0
def stream_template(template_name, **context):
    current_app.update_template_context(context)
    t = current_app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    rv.enable_buffering(5)
    return rv
示例#25
0
def stream_template(template_name, **context):
    current_app.update_template_context(context)
    t = current_app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    rv.enable_buffering(5)
    return rv