python - 如何使 Flask 在 HTML 中运行函数并在同一页面上打印结果?
问题描述
我一直在尝试使用我之前编写的脚本将阿拉伯数字转换为罗马数字。用户输入数字,我的脚本将它们转换为罗马数字。脚本运行良好,但我试图将其嵌入网页并没有按预期工作。我在谷歌上搜索了解决方案,每个人都告诉我需要从表单中获取价值,我这样做了:
<form action="toroman" method="POST">
<input type="number" name="arabic" onChange="toroman(this.value)" oninput="toroman(this.value)">
<p>{{ romanfinal }}</p>
</form>
这是我的 server.py 应该打印出同一页面的编号,但它没有这样做,而是当我在提交值时按“Enter”时,它会创建一个新页面并显示正确的答案。
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/toroman", methods=['POST'])
def toroman():
arabic = request.form['arabic']
# some unnecessarily numerous lines of code that basically turn Arabic-system number to Roman system
return romanfinal
if __name__ == "__main__":
app.run(debug=True)
这就像它真正起作用的唯一一次,当我尝试将其更改为其他内容时,它只会给我错误。请告诉我我到底有什么不明白的。
解决方案
您的toroman():
函数应返回带有参数的 index.html:
@app.route("/toroman", methods=['POST'])
def toroman():
arabic = request.form['arabic']
# some unnecessarily numerous lines of code that basically turn Arabic-system number to Roman system
return render_template("index.html", data = romanfinal)
然后,您可以data
像这样在 HTML 顶级中使用该值:{{data}}
推荐阅读
- postgresql - 将变量从一个 sql 脚本传递到另一个作为 postgres sql 中的参数
- firebase - 如何在 Flutter 中查询其字段值包含在本地列表变量中的 Firestore 数据
- c# - 使用 linq 排序、区分并选择前 5 个结果
- powershell - Test-WSMan 上的 if/else 语句
- javascript - 从有效负载中删除密钥
- google-sheets - 与多个工作表相比,识别列表中的新项目
- ansible - import_role 和 include_role 在变量优先级方面的区别
- reactjs - 在循环中将项目添加到状态数组
- reactjs - yup.js 验证数字字段大于兄弟,或可为空
- jinja2 - 块和块周围的jinja2空白控制