Flask:如何将数据从python脚本发送到HTML [英] Flask: How to send data from python script to HTML

查看:66
本文介绍了Flask:如何将数据从python脚本发送到HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回列表的python脚本,我想将这些数据发送到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:

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

现在,我想在某些模板中接收此脚本.有人可以帮我吗?

Now I want to receive this script in some template. Anyone can help me with that?

推荐答案

您想要这样的东西:

script.py

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

index.html

{%for i in to_send%}
<p> {{i[0]}}</p>
{%endfor%}

这篇关于Flask:如何将数据从python脚本发送到HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆