Flask: How To Send Data From Python Script To Html
I have a python script returning a list and I would like to send those data to HTML for building a appropriate template. script.py: def database(): try: conn = psycopg2.connect(
Solution 1:
You want something like this:
script.py
def database():
try:
conn = psycopg2.connect("dbname='DataTeste' user='user1' host='localhost' password='123'")
except:
return"Impossible to connect to the database, check your code."
cur = conn.cursor()
conn.set_client_encoding('LATIN1')
cur.execute("SELECT * FROM customers")
rows = cur.fetchall()
return rows
index.py
from flask import render_template
from script import database
@app.route("/")defindex():
to_send=database()
return render_template("index.html", to_send=to_send)
index.html
{%for i in to_send%}
<p> {{i[0]}}</p>
{%endfor%}
Solution 2:
You should look in http://jinja.pocoo.org/docs/2.10/ documentation. It's really simple.
Here is how to do it.
Python file
from flask import render_template
@app.route("/")defindex():
list_object = ["Hey", "How", "Are", "You"]
return render_template("index.html", list_to_send=list_object)
HTML file "index.html"
Put this in body
tag.
{% for element in list_to_send%}
<p>{{element}}</p>
{% endfor %}
Post a Comment for "Flask: How To Send Data From Python Script To Html"