首页 > 解决方案 > 如何将 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)

标签: pythonhtmlcssflaskweb

解决方案


您可以将变量从烧瓶传递到您的模板:

 <!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 文件中的匹配。


推荐阅读