Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1579

Python • Re: Python / Flask server not displaying embedded text data on served out HTML file

$
0
0
I'm kinda confused with this execution and embedding of python. You're in python? Why don't you create a route for the pin.py (and it doesn't even have to exist) and embed your code in the route?

Code:

from flask import Flask,render_template,Responsefrom random import randrangefrom json import dumpsdef jsonReturn(data):return Response(dumps(data),mimetype="application/json")app=Flask(__name__)@app.route("/")def home():    return render_template("index.html")@app.route("/pin.py")def pin():    return jsonReturn(list((randrange(20,100) for x in range(10))))if __name__=='__main__':     app.run(host="127.0.0.2",port=8080,debug=True)
And in your HTML, do some JS:

Code:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>PIN</title>    <script>        document.addEventListener(`DOMContentLoaded`,async _=>{            await pin();            setInterval(pin,3000);        });        async function pin(){            if(document.querySelector(`#pin_ul`)) document.querySelector(`#pin_ul`).remove();            const res=await fetch(`/pin.py`);            try {                const json=await res.json();                const pin_el=document.createElement(`ul`);                pin_el.id=`pin_ul`;                pin_el.style.listStyleType=`none`;                for(const x of json){                    const li=document.createElement(`li`);                    li.innerText=x;                    pin_el.append(li);                }                document.body.append(pin_el);            } catch{}        }    </script></head><body></body></html>
Which will update the HTML every 3ish seconds. The `pin.py` doesn't even exist on the filesystem in this example.

Statistics: Posted by valkyrie44 — Sat Dec 27, 2025 6:20 pm



Viewing all articles
Browse latest Browse all 1579

Trending Articles