我有一个返回列表的python脚本,我想将这些数据发送到HTML以构建适当的模板。
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
现在我想在某个模板中收到此脚本。任何人都可以帮助我吗?
答案 0 :(得分:1)
您应该查看http://jinja.pocoo.org/docs/2.10/文档。这很简单。
以下是如何做到的。
from flask import render_template
@app.route("/")
def index():
list_object = ["Hey", "How", "Are", "You"]
return render_template("index.html", list_to_send=list_object)
将其放入body
标记。
{% for element in list_to_send%}
<p>{{element}}</p>
{% endfor %}
答案 1 :(得分:1)
你想要这样的东西:
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("/")
def index():
to_send=database()
return render_template("index.html", to_send=to_send)
的index.html
{%for i in to_send%}
<p> {{i[0]}}</p>
{%endfor%}