5

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

5
  • you would need JavaScript /AJAX on page which periodically sends request for new content and Flask should send current content. Commented Nov 22, 2019 at 15:16
  • eventually you could use <meta http-equiv="refresh" content="2"> to reload page every 2 seconds Commented Nov 22, 2019 at 15:19
  • @furas I've thought of the auto refresh but it is distracting, I'll look into AJAX to update the page Commented Nov 22, 2019 at 15:34
  • BTW: jQuery.get() to send requestfrom JavaScript (AJAX) to server. But probably it could be made without jQuery but it wouldn't as easy as with jQuery. Commented Nov 22, 2019 at 16:02
  • strip("\n") is redundant. Just strip() will do the job. Commented Nov 23, 2019 at 14:15

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.