Update Flask web page with python script

Question:

Program description: I already have a functioning program that runs on console window, but I’d like to present its output on a locally hosted web page. The program consists on getting lyrics for currently playing songs by making requests to Spotify’s API. I store the current lyrics in a “lyrics.txt” file.

What I want:

Change the web page from the running lyrics program when it detects the song has changed.

[EDIT:]

Is there a way to make the flask page display a variable, that is updated by a python request.post of the lyrics app to the flask url with the updated variable as the data?

What I have:

I’m using Flask as the framework since its a one local web page.

import os, io
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def test():
    '''reads the current lyrics file and passes it to the web page
    manually reload the page to update lyrics'''
    with io.open('lyrics.txt', 'r') as f:
        HEAD = f.readline().strip("n")
        BODY = f.read().split('n')

    lyrics = {"HEAD": HEAD, "BODY": BODY}
    return render_template("home.html", lyrics=lyrics)


if __name__ == "__main__":
    app.run(debug=1)

link to lyrics app github

Asked By: Gustavo Barros

||

Answers:

You would need JavaScript/AJAX on page which periodically sends request for new content and Flask should send current content from file.


In this example I use jQuery.get() to send request to server, and setTimeout() to repeat it periodically.

Flask sends current time to show different content.

import datetime
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template_string("""<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title>Test</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>

<script type="text/javascript">
function updater() {
  $.get('/data', function(data) {
    $('#time').html(data);  // update page with new data
  });
};

setInterval(updater, 1000);  // run `updater()` every 1000ms (1s)
</script>

</head>

<body>
Date & Time: <span id="time"><span>
</body>

</html>""")


@app.route('/data')
def data():
    """send current content"""
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

if __name__ == "__main__":
    app.run(debug=True)

EDIT:

The same using standard fetch() without external libraries.

Code has to be after <span>

import datetime
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template_string("""<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title>Test</title>
</head>

<body>

Date & Time: <span id="time"><span>

<script type="text/javascript">
var time_span = document.getElementById("time");

function updater() {
  fetch('/data')
  .then(response => response.text())
  .then(text => (time_span.innerHTML = text));  // update page with new data
}

setInterval(updater, 1000);  // run `updater()` every 1000ms (1s)
</script>

</body>

</html>""")


@app.route('/data')
def data():
    """send current content"""
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

if __name__ == "__main__":
    app.run(debug=True)
Answered By: furas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.