python - 如何将 python 函数添加到 HTML 中?
问题描述
我正在使用 Python 烧瓶编写一个网站。它必须读取一个 csv 文件(保存为 csv 的 excel 文件),在那里进行一些计算,并且我需要在网站上显示实际表格和结果。如何在 html 文件中编写函数?我需要把它们写在“一些桌子”的地方。这是我的html文件:
<!doctype html>
<html lang="ru">
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<div class="container">
<nav class="navbar">
<ul>
<li><a href="#table">first</a></li>
<li><a href="#problems">second</a></li>
<li><a href="#rank">third</a></li>
<li><a href="#cheated">forth</a></li>
</ul>
</nav>
<section id="table">
<h1>1</h1>
<p class="lead"> some table</p>
</section>
<section id="problems">
<h1>2</h1>
<p class="lead">some table</p>
</section>
<section id="rank">
<h1>3</h1>
<p class="lead">some table</p>
</section>
<section id="cheated">
<h1>4</h1>
<p class="lead">some table</p>
</section>
</div>
</html>
这是我的 py 文件
from flask import Flask, render_template
from flask import url_for
from flask import make_response, request, redirect
import io
import csv
from io import TextIOWrapper
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
with open('testfinal.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
print(csv_reader)
@app.route('/')
def about():
return render_template("about.html")
if __name__ == "__main__":
app.run(debug=True)
解决方案
您可以将变量从烧瓶传递到您的模板:
<!doctype html>
<html lang="ru">
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<div class="container">
<nav class="navbar">
<ul>
<li><a href="#table">first</a></li>
<li><a href="#problems">second</a></li>
<li><a href="#rank">third</a></li>
<li><a href="#cheated">forth</a></li>
</ul>
</nav>
<section id="table">
<h1>1</h1>
<p class="lead">{{ some_table }} some table</p>
</section>
<section id="problems">
<h1>2</h1>
<p class="lead"> {{ some_table }} some table</p>
</section>
<section id="rank">
<h1>3</h1>
<p class="lead">{{ some_table }} some table</p>
</section>
<section id="cheated">
<h1>4</h1>
<p class="lead"> {{ some_table }}some table</p>
</section>
</div>
</html>
然后在您的服务器(python)中:
from flask import Flask, render_template
from flask import url_for
from flask import make_response, request, redirect
import io
import csv
from io import TextIOWrapper
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
@app.route('/')
def about():
with open('testfinal.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
print(csv_reader)
return render_template("about.html", some_table=csv_reader)
if __name__ == "__main__":
app.run(debug=True)
注意:some_table=
在 python 烧瓶中应该与{{ some_table }}
html 文件中的匹配。
推荐阅读
- amazon-web-services - AWS HTTP API Gateway 基于 URL 的路由
- recursion - 获取堆栈溢出的函数的递归迭代
- javascript - NodeList 的长度不一致
- python - 使用 python argschema 解析位置 cli args
- automation - 从 Access 到文本框输入字母数字值 - VBScript - Powerbuilder
- vba - vba 提取期间的高内存利用率问题
- cloud-foundry - 无法使用 cli 登录 Cloud Foundry
- go - 在 Go 中加载地图元素是否意味着复制?
- node.js - HTML Pdf转换器在windows中工作正常,但在linux中使用nodejs?
- python - 我想从一个 Odoo 实例(单击按钮)重定向到另一个 Odoo 实例。另外,想在登录后在第二个实例上打开向导