app.py
import flask
from flask import Flask, render_template, request
# 计算精确的浮点结果,float加法也计算不出来
from decimal import Decimal
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/calculate', methods=['POST'])
# POST请求处理用户提交的数据
def calculate():
num1 = Decimal(request.form['num1'])
num2 = Decimal(request.form['num2'])
operation = request.form['operation']
result = Decimal(0)
# 输入的两个数和运算符,结果初始为0
if operation == 'add':
result = num1 + num2
# 加
elif operation == 'subtract':
result = num1 - num2
# 减
elif operation == 'multiply':
result = num1 * num2
# 乘
elif operation == 'divide':
if num2 != Decimal(0):
result = num1 / num2
else:
return "错误:分母不能为0"
# 除
result = round(result,4)
# 保留四位小数
return render_template('result.html', num1=num1, num2=num2, operation=operation, result=result)
# 然后将计算结果和输入的两个参数返回给result.html渲染
if __name__ == '__main__':
app.run(debug=True)
templates文件夹
index.html
<!DOCTYPE html>
<html>
<head>
<title>在线计算器</title>
</head>
<body>
<h1>在线计算器</h1>
<form action="/calculate" method="POST">
<!-- 获得请求 -->
<input type="text" name="num1" required>
<select name="operation" required>
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
<!-- 加减乘除的操作 -->
</select>
<input type="text" name="num2" required>
<button type="submit">开始计算</button>
<!-- 提交表单 -->
</form>
</body>
</html>
<!-- type="number" 时,浏览器会为输入字段提供一些额外的验证和用户界面上的增强功能,
例如限制输入为数值、显示数值调节器控件等。 -->
result.html
<!DOCTYPE html>
<html>
<head>
<title>计算结果</title>
</head>
<body>
<h1>计算结果</h1>
<p>{{ num1 }} {{ operation }} {{ num2 }} = {{ result }}</p>
<!-- 执行相关的计算操作的变量 -->
</body>
</html>
实现效果
支持小数点计算