Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continuously display python output in a webpage?

I want to be able to visit a webpage and it will run a python function and display the progress in the webpage.

So when you visit the webpage you can see the output of the script as if you ran it from the command line and see the output in the command line.

What do I need to do in the function?

What do I need to do in the template?

EDIT:

I am trying to use Markus Unterwaditzer's code with a template.

{% extends "base.html" %}
{% block content %}

{% autoescape false %}

{{word}}

{% endautoescape %}

{% endblock %}

Python code

import flask
from flask import render_template
import subprocess
import time

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        for x in range(1000):
            yield '%s<br/>\n' % x
            time.sleep(1)
    return render_template('simple.html', word=inner())
    #return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show the partial page immediately

app.run(debug=True, port=8080)

And it runs but I don't see anything in the browser.

like image 501
Siecje Avatar asked Feb 23 '13 14:02

Siecje


1 Answers

Here is a very simple app that streams a process' output with normal HTTP:

import flask
import time

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        for x in range(100):
            time.sleep(1)
            yield '%s<br/>\n' % x
    return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show the partial page immediately

app.run(debug=True)
like image 86
Markus Unterwaditzer Avatar answered Oct 21 '22 22:10

Markus Unterwaditzer