Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8900923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T01:13:14+00:00 2026-06-15T01:13:14+00:00

I can’t seem to figure out how to using Flask’s streaming. Here’s my code:

  • 0

I can’t seem to figure out how to using Flask’s streaming. Here’s my code:

@app.route('/scans/')
def scans_query():
    url_for('static', filename='.*')
    def generate():
        yield render_template('scans.html')
        for i in xrange(50):
            sleep(.5)
            yield render_template('scans.html', **locals())
    return Response(stream_with_context(generate()))

and in my template:

<p>{% i %}</p>

I would like to see a counter on the page that changes every half second. Instead, the closest I’ve gotten is the page printing out each number on the next line.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T01:13:15+00:00Added an answer on June 15, 2026 at 1:13 am

    To replace existing content on the page you might need javascript i.e., you could send it or make it to make requests for you, use long polling, websockets, etc. There are many ways to do it, here’s one that uses server send events:

    #!/usr/bin/env python
    import itertools
    import time
    from flask import Flask, Response, redirect, request, url_for
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        if request.headers.get('accept') == 'text/event-stream':
            def events():
                for i, c in enumerate(itertools.cycle('\|/-')):
                    yield "data: %s %d\n\n" % (c, i)
                    time.sleep(.1)  # an artificial delay
            return Response(events(), content_type='text/event-stream')
        return redirect(url_for('static', filename='index.html'))
    
    if __name__ == "__main__":
        app.run(host='localhost', port=23423)
    

    Where static/index.html:

    <!doctype html>
    <title>Server Send Events Demo</title>
    <style>
      #data {
        text-align: center;
      }
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    if (!!window.EventSource) {
      var source = new EventSource('/');
      source.onmessage = function(e) {
        $("#data").text(e.data);
      }
    }
    </script>
    <div id="data">nothing received yet</div>
    

    The browser reconnects by default in 3 seconds if the connection is lost. if there is nothing more to send the server could return 404 or just send some other than 'text/event-stream' content type in response to the next request. To stop on the client side even if the server has more data you could call source.close().

    Note: if the stream is not meant to be infinite then use other techniques (not SSE) e.g., send javascript snippets to replace the text (infinite <iframe> technique):

    #!/usr/bin/env python
    import time
    from flask import Flask, Response
    
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
        def g():
            yield """<!doctype html>
    <title>Send javascript snippets demo</title>
    <style>
      #data {
        text-align: center;
      }
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <div id="data">nothing received yet</div>
    """
    
            for i, c in enumerate("hello"):
                yield """
    <script>
      $("#data").text("{i} {c}")
    </script>
    """.format(i=i, c=c)
                time.sleep(1)  # an artificial delay
        return Response(g())
    
    
    if __name__ == "__main__":
        app.run(host='localhost', port=23423)
    

    I’ve inlined the html here to show that there is nothing more to it (no magic). Here’s the same as above but using templates:

    #!/usr/bin/env python
    import time
    from flask import Flask, Response
    
    app = Flask(__name__)
    
    
    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
    
    
    @app.route('/')
    def index():
        def g():
            for i, c in enumerate("hello"*10):
                time.sleep(.1)  # an artificial delay
                yield i, c
        return Response(stream_template('index.html', data=g()))
    
    
    if __name__ == "__main__":
        app.run(host='localhost', port=23423)
    

    Where templates/index.html:

    <!doctype html>
    <title>Send javascript with template demo</title>
    <style>
      #data {
        text-align: center;
      }
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <div id="data">nothing received yet</div>
    {% for i, c in data: %}
    <script>
      $("#data").text("{{ i }} {{ c }}")
    </script>
    {% endfor %}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can't seem to figure out what's wrong with the simple getJSON call below. It's
Can someone thoroughly explain the last line of the following code: def myMethod(self): #
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Can I authenticate with just Google account username and password instead of using OAuth?
Can we change the default action of the edit selected row button? Here is
Can PHP PDO extension bind nested objects automatically ? I mean using foreign key
Can i get the source code for a WAMP stack installer somewhere? Any help
Can a LINQ enabled app run on a machine that only has the .NET
Can someone tell me how does the imdb app manage to play trailers on
We're building an app, our first using Rails 3, and we're having to build

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.