flask 单个网页实现加法运算
时间: 2023-07-11 10:04:57 浏览: 60
好的,下面是一个简单的 Flask 应用,实现了加法运算。你可以将以下代码保存为 `app.py` 文件并运行。
```python
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def add():
if request.method == 'POST':
num1 = int(request.form['num1'])
num2 = int(request.form['num2'])
result = num1 + num2
return render_template('index.html', result=result)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
```
其中,`@app.route('/')` 指定了根路径,即网站的首页。当收到 GET 请求时,会渲染 `index.html` 模板,并返回给浏览器;当收到 POST 请求时,会从表单中获取两个数值,计算它们的和,然后再次渲染 `index.html` 模板,并将结果传递给模板。
在同级目录下创建一个名为 `templates` 的文件夹,并在该文件夹中创建一个名为 `index.html` 的模板文件,内容如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Addition</title>
</head>
<body>
<h1>Addition</h1>
<form method="POST">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1"><br><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" name="num2"><br><br>
<input type="submit" value="Add">
</form>
{% if result %}
<h2>Result: {{ result }}</h2>
{% endif %}
</body>
</html>
```
该模板文件包含一个表单,用户可以输入两个数值,然后提交表单。如果有计算结果,模板会显示出来。
现在,在终端中运行以下命令启动 Flask 应用:
```bash
$ python app.py
```
然后,在浏览器中访问 `http://localhost:5000/`,即可使用该应用进行加法运算。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)