python - 如何使用 Flask 从 Postgresql 数据库中获取数据并显示 HTML 表
问题描述
import psycopg2
from flask import Flask, render_template
app = Flask(__name__)
con = psycopg2.connect(database="Angels_Attic", user="postgres", password="", host="127.0.0.1", port="5432")
cursor = con.cursor()
@app.route("/", methods=['post', 'get'])
def test():
cursor.execute("select * from cart")
result = cursor.fetchall()
return render_template("test.html", data=result)
测试.html
<html>
<body>
<div>
{% for row in data %}
<p>{{ row[0] }}</p>
<p>{{ row[1] }}</p>
{% endfor %}
</div>
</body>
</html>
我得到的错误:IndentationError: unindent does not match any external indentation level
当我运行这个烧瓶文件时,我遇到了一堆错误。我只想知道如何正确连接数据库并使用复杂的 SQL 查询从中获取数据并将其显示在 HTML 文件中。请让我知道如何进行。
解决方案
这与代码的逻辑无关,只是代码的缩进应该是这样的:从import下面的所有行中删除空格
import psycopg2
from flask import Flask, render_template
app = Flask(__name__)
con = psycopg2.connect(database="Angels_Attic", user="postgres", password="", host="127.0.0.1", port="5432")
cursor = con.cursor()
@app.route("/", methods=['post', 'get'])
def test():
cursor.execute("select * from cart")
result = cursor.fetchall()
return render_template("test.html", data=result)
推荐阅读
- xslt - XSL 根据另一个文件中元素数据的存在来修改输出
- r - R中带有ggplot2的背靠背条形图
- django - 带有 chart.js 的 Django 图表
- image - 如何定义要在响应式容器中使用的图像的最小分辨率?
- apache-spark - 使用动态分隔符解析 Spark 文本
- varnish - 如何使用 Vmod Xkey 使缓存中的对象无效
- python - 使用脊和散点图进行数据可视化
- javascript - 自定义加载器功能尝试导航到根页面失败
- javascript - 输入 3 个反引号 ``` 后,Quill 将输入转换为代码块
- java - 从给定的 YAML 动态生成 Java 测试类