我有非常简单的代码 - 我正在寻找更好的解决方案我的情况:我有: - 2输入文本+提交按钮
输入表单始终将文本返回为字符串。你知道更好的解决方案(和更短的)只传递数值(和非数字 - 显示“错误”)除了收集列表中的所有字母和检查语句,如果输入的文字不在字母列表中?
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/licz/", methods=['GET'])
def search():
licz1 = request.args.get('liczba1')
licz2 = request.args.get('liczba2')
notnumbers = ['q','w','e','r','t','y']
if licz1 and licz2 != None:
if licz1 not in notnumbers:
sumaliczenia = int(licz1) + int(licz2)
return render_template('liczenie.html', suma=sumaliczenia)
else:
sumaliczenia = "error"
return render_template('liczenie.html', suma=sumaliczenia)
else:
return render_template('liczenie.html')
app.run(debug=True)
模板代码(来自下面的评论):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Formularz</title>
</head>
<body> Result is {{ suma }}
<form action="/licz/" method="get">
<input type="text" name="liczba1">
<input type="text" name="liczba2"> <button type="submit">Send</button>
</form>
</body>
</html>
您可以尝试将输入转换为int。如果没有数值,Python将引发一个ValueError,您可以捕获并执行错误。
try:
input1 = int(input1)
input2 = int(input2)
except ValueError as e:
# print error
else:
# valid
sum = input1 + input2