【发布时间】:2021-03-29 16:13:22
【问题描述】:
我对网络开发(第一个项目)非常陌生,并且已经开始在 Flask 中玩耍。前几天我做了一个非常简单的温度转换器,我在本地主机上运行它。该页面有一个输入值的表单输入,两个带有华氏温度和摄氏温度的单选按钮来定义值的系统,然后是一个转换按钮。这是截图:
这是我的 Flask 代码(“main.py”):
from flask import Flask, render_template
from flask import request, redirect
import temperature, convert, determine_system
app = Flask(__name__)
@app.route('/')
def html():
return render_template('index.html')
@app.route('/convert', methods = ['POST'])
def convert():
temp = request.form['temperature']
system = request.form['system']
new_temp, destination_system = determine_system.determine_system(temp, system)
return render_template('convert.html', temp=temp, system=system, new_temp=new_temp, destination_system=destination_system)
if __name__ == "__main__":
app.run()
如您所见,名为“html()”的第一个函数最初呈现“index.html”文件,并在单击“转换”按钮时执行函数“convert()”。我在目录中的其他 .py 文件中还有一些其他功能可以将数字转换为新系统。
这是我的“index.html”代码的主体:
<body>
<div id="banner">
<h1>Temperature Converter</h1>
<p class="lead">Use this tool to convert temperature between measurement systems</p>
</div>
<form action="/convert" method="post" target="dummyframe">
<input type="text" name="temperature"></input>
<input type="radio" name="system" value="Fahrenheit">Fahrenheit</input>
<input type="radio" name="system" value="Celsius">Celsius</input>
<br>
<br>
<input type="submit" value="Convert"></input>
</form>
</body>
</html>
为了在网页上显示转换后的温度,我目前在我的模板目录中有另一个名为“convert.html”的 HTML 文件,它是“index.html”文件的精确副本,除了它包含以下三行正文中的代码:
div id="output"></div>
<p class="output-statement">{{ temp }}° {{ system }} is equal to {{ new_temp }}° {{ destination_system }}</p>
</div>
在我的 Flask 文件(“main.py”)中,我指示“convert()”函数渲染“convert.html”模板,该模板包含上面代码中的输出语句:
return render_template('convert.html', temp=temp, system=system, new_temp=new_temp, destination_system=destination_system)
这会产生以下结果(注意新的网址):
我怀疑我通过重定向到新的 HTML 文件和网址 (http://127.0.0.1:5000/convert) 来输出转换后的温度的方式效率不高,甚至是显示完成此操作的正确方式。输出这样的东西的正确方法是什么?有什么我可以添加到“index.html”文件中的东西,可以让我完全摆脱“convert.html”文件吗?如果是这样,我会将 Flask(“main.py”)文件中“convert()”函数的最后一行更改为什么?
提前感谢您,非常感谢您提供有关此概念的更多信息的任何链接!
【问题讨论】:
标签: python html css flask python-requests