Streaming an iterable and other variable in Flask using Jinja

Viewed 21

I have a long process that I managed to stream into a Jinja template, but now I would like to show not only results but also that could be viewed by the user as a meaning of progress.

This is my current code: it iterates over a huge collection of items, some of which produce results and others do not. I only want to show the items that match the search.

The rendering part:

lista_pantallas = buscar_componente_stream_generate(componente, atributo, valor)
return Response(stream_template('consultas/busqueda_comp.html',
                           lista_pantallas=lista_pantallas,
                           componente=componente, atributo=atributo, valor=valor,
                           error_msg=err_msg))

This is the way I generate the iterator:

def buscar_componente_stream_generate(componente, atributo, valor):
    with uopy.connect(...) as session:
        with uopy.File(...) as fapant:
            pantallas_fmpant = uopy.List() 
            pantallas_fmpant.select(fapant)
            functor = BuscadorObjetoAtributo(componente, atributo, valor)
            for idx, pantalla in enumerate(pantallas_fmpant):
                try:
                    if print_pant:
                        print(f'{idx} - Pantalla: {pantalla}')
                    procesar_pantalla(pantalla, functor)
                    for item in functor.lista_objetos():
                        yield item
                    functor.borrar_objetos()
                except Exception as ex:
                    print('{0} - {1} - {2}'.format(idx, pantalla, str(ex)))

And the Jinja2 template

    {% if lista_pantallas %}
        <h1>Lista de pantallas</h1>
        <h2>Condición: {{ componente }}.{{ atributo }} = {{ valor }}</h2>
        <h2>Ultima pantalla procesada: {{idx}} - {{pantalla}}</h2>
        <table>
            <thead>
                <th>Pantalla</th>
                <th>Atributo</th>
            </thead>
            <tbody>
        {% for item in lista_pantallas %}
            {% if loop.index0 is even() %}
                {% set par_css = 'par' %}
            {% else %}
                {% set par_css = 'impar' %}
            {% endif %}
            <tr class={{ par_css }}>
                <td>{{ item['fichero'] }}</td>
                <td>{{ item['prop'] }}</td>
            </tr>
        {% endfor %}
            </tbody>
        </table>
    {% endif %}

How can I refresh the template with the values of the variables idx and pantalla?

0 Answers
Related