在flask中,如何使用python代码修改html?

2024-04-24 15:11:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这是“apprunner.py“我的酒瓶

   from flask import *
   from flaskext.mysql import MySQL

   enter code hereapp = Flask(__name__)


   mysql = MySQL()
   app.config['MYSQL_DATABASE_USER'] = 'root'
   app.config['MYSQL_DATABASE_PASSWORD'] = 'myPassword'
   app.config['MYSQL_DATABASE_DB'] = 'myDB'
   app.config['MYSQL_DATABASE_HOST'] = 'localhost'
   mysql.init_app(app)



  conn = mysql.connect()
  cursor =conn.cursor()

  cursor.execute("SELECT * from clients")
  data = cursor.fetchall()



 @app.route("/")
 def index():
   return render_template("index.html")

 if __name__ == "__main__":
   app.run(debug=True)

这是我的索引.html文件:

^{pr2}$

在“的数据变量中apprunner.py文件,它以元组的形式包含“clients”表的所有条目。我要做的是将clients表中的clients信息加载到html文件中id为“info_section”的块中。如何在python中实现它?在


Tags: 文件namefrompyimportconfigapphtml
1条回答
网友
1楼 · 发布于 2024-04-24 15:11:16

您需要像这样将数据传递给模板。在

return render_template("index.html", data=data)

然后在HTML文件中,可以像这样循环遍历数据。在

<div id='info_section'>
    {% for data in data %}
        <p>{{ data }}</p>
    {% endfor %}
</div>

如果要访问条目的列,可以执行<p>{{ data.whatever_attribute }}</p>

相关问题 更多 >