如何使用MySQL數據庫中的值填充HTML中的{{}}。該應用程序使用Flask,Python版本2.7.13編寫。燒瓶0.12.2Flask HTML模板填寫MySQL記錄
當瀏覽到http://127.0.0.1:5000/emp我只拿到硬編碼的HTML標籤。
我想透過瓶框架,以顯示員工ID,名字和姓氏的HTML表
請參閱下面的Python代碼:
from flask import Flask, request, render_template
import MySQLdb
app = Flask(__name__)
def db():
db = MySQLdb.connect(host="localhost",
user="someone",
passwd="something",
db="inventory")
cursor = db.cursor()
cursor.execute("SELECT ID, First_Name, Last_Name from employees")
rows = cursor.fetchall()
db.close()
return rows
rows = db()
for row in rows:
#print(row)
print str(row[0]) + " - " + row[1] + " " + row[2]
@app.route('/emp', methods=['GET'])
def emp():
return render_template ('inventory.html')
if __name__ == '__main__':
app.run(debug = True)
下面是HTML模板
<!doctype html>
<html lang="en">
<head>
<meta charset = "utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<title>Inventory Database</title>
<style type="text/css">
body { background-color: white; }
</style>
</head>
<body class="body">
<div class="jumbotron text-center">
<div class="page-header">
<h3 class="text-primary">Inventory Management Database: All Employees </h3>
</div>
<table class="table table-striped table-bordered table-hover">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<th>1</th>
<th>Omar</th>
<th>Qouqas</th>
</tr>
{% for emp in employees %}
<tr>
<td>{{ID}}</td>
<td>{{First_Name}}</td>
<td>{{Last_Name}}</td>
</tr>
{% endfor %}
</table>
</div>
</body>
</html>
請閱讀[官方燒瓶教程](http://flask.pocoo.org/docs/0.12/tutorial/views/),它解釋了這個詳細。 –