【问题标题】:Flask: How to send data from python script to HTML [closed]Flask:如何将数据从 python 脚本发送到 HTML [关闭]
【发布时间】:2018-07-25 12:43:15
【问题描述】:

我有一个 python 脚本返回一个列表,我想将这些数据发送到 HTML 以构建适当的模板。

脚本.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

现在我想在某个模板中接收这个脚本。任何人都可以帮助我吗?

【问题讨论】:

  • 使用Jinja
  • 您确实需要为您的问题添加更多细节。 Flask 预装了一个模板库Jinja2,您可以使用它来呈现 HTML 模板。它还能够将 json 数据返回到 AJAX 调用...如果您包含 Minimal, Complete, and Verifiable example,您将获得更多相关响应
  • 渲染模板
  • 渲染模板对我来说很清楚,我将 python 脚本数据发送到一些我没有找到的模板

标签: python flask


【解决方案1】:

你想要这样的东西:

脚本.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%}

【讨论】:

  • 成功了!为我清除它,from "script_name" import "function_name"。是吗?
  • 是的,就是这样工作的
【解决方案2】:

您应该查看http://jinja.pocoo.org/docs/2.10/ 文档。真的很简单。

这是怎么做的。

Python 文件

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)

HTML 文件“index.html”

把这个放在body标签中。

{% for element in list_to_send%}
    <p>{{element}}</p>
{% endfor %}

【讨论】:

  • list_object 在 script.py 中,是否需要在最终函数中返回列表并在 render_template 中将其作为 arg 调用?
猜你喜欢
  • 2012-07-18
相关资源
最近更新 更多