英文:
Display data on html from mysql database using flask
问题
以下是翻译好的代码部分:
我一直卡在如何使用Flask从MySQL数据库显示数据在HTML上。
我的数据库连接成功,HTML页面可以显示,只是没有显示数据。
想要显示数据库中的“info_table”。它有两个属性“name”和“age”。
是否正确使用了“app.route('/display', methods=['GET'])”?
app.py
display.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<style>
td {
width: 150px;
text-align: center;
border: 1px solid black;
padding: 5px;
}
</style>
<table>
<thead>
<tr>
<th>name</th>
<th>age </th>
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
英文:
I been stuck on how to display data on html from mysql database using flask.
My connection to database is successful and html page displays. Just doesn't display with the data
Would like to display the "info_table" from the database. Has 2 attribute "name" and "age"
Is line "app.route('/display', methods=['GET'])" correct?
app.py
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.debug = True
app.config['MYSQL_HOST'] = ''
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'DB'
mysql = MySQL(app)
app.route('/display', methods=['GET'])
def display():
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM info_table")
data = cursor.fetchall()
return render_template('display.html', info_table=data)
app.run(host='localhost', port=3306)
display.html:
t<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<style>
td {
width: 150px;
text-align: center;
border: 1px solid black;
padding: 5px;
}
</style>
<table>
<thead>
<tr>
<th>name</th>
<th>age </th>
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
答案1
得分: 0
首先,我需要感谢你一直在尝试和提问。
关于app.py
中的请求处理程序app.route('/display', methods=['GET'])
,你应该将其定义为装饰器,像这样@app.route('/display', methods=['GET'])
,然后在display.html
中,在for
循环中将data
变量更改为info_table
,因为这是你正在映射数据的真正属性。
英文:
First of all I need to thank you that you're keep trying and asking.
Regarding request handler in app.py
app.route('/display', methods=['GET'])
you should define it as a decorator like this
@app.route('/display', methods=['GET'])
and then in display.html
change the data
variable to info_table
in the for loop cause this is the real attribute that you're mapping data to it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论