python - 如何从我的 Flask python 应用程序查询数据库?
问题描述
到目前为止,我已经成功地将我的代码连接到我要查询的 MariaDB 数据库:
from flask import Flask, render_template, request, flash
import mysql.connector
from datetime import date
import mariadb
app = Flask(__name__)
conn = mariadb.connect(host='IP', port= 3306, user='user', password='password', database='myDatabase')
cursor = conn.cursor()
result = cursor.execute('SELECT * FROM myTable LIMIT 10')
@app.route('/')
def index():
return result
return render_template('index.html')
# run the app.
if __name__ == "__main__":
# Setting debug to True enables debug output. This line should be
# removed before deploying a production app.
app.debug = True
app.run()
如何让查询显示在此 Web 应用程序的 HTML 页面上?
解决方案
你应该在任何教程中得到它。
您必须将结果render_template
作为参数发送
@app.route('/')
def index():
results = result.fetchall() # get all rows
return render_template('index.html', data=results)
接下来你可以使用 name data
inHTML
来显示它。
{{ data }}
您可以for
在模板中使用 -loop 对其进行格式化。
<tabel>
{% for row in data %}
<tr>
{% for item in row %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
在render_template
您可以使用任何名称 - 即。all_values=data
- 并{{ all_values }}
用于HTML
推荐阅读
- c# - 插入两个表,其中一个表具有自动增量主键,并且该相同键用作另一个表中的外键
- python - 带有 ubtuntu:trusty 的 Docker 并安装 python-dev
- uwp - UWP 应用每 30 秒冻结一次
- python - python日志记录中字符串的延迟评估:比较`%`和`.format`
- php - 合并两个 Sql 语句
- ios - ld:找不到带有 pod 的 -lreact-native-fetch-blob 的库?
- python - 内存错误熊猫
- unity3d - NullReferenceException:对象引用未设置为对象 UiManager.Update () 的实例(在 Assets/UiManager.cs:32)
- ruby-on-rails - Rails 5.2 的活动存储没有方法错误
- swift4 - 当用户点击 UITextview 中的单词时,有没有办法创建弹出框