Python货币转换器Decimal Float不匹配错误



我试图用Python/Flask构建一个非常简单的货币转换器。我用的是一个叫做forex-python的库。当我在命令行中尝试使用ipython时。一切都很好:

In [1]: from forex_python.converter import CurrencyRates
In [2]: c = CurrencyRates()
In [3]: c.convert('USD', 'EUR', 10)
Out[3]: 8.259002313

很棒!但是,当我通过运行flask服务器并在浏览器中执行此操作时,它不起作用。我在index.html中的表单是这样的:

<form action="/results" method="post">
<p>Converting from <input type="text" name="convert_from" placeholder="USD"></p>
<p>Converting to <input type="text" name="convert_to" placeholder="EUR"></p>
<p>Amount <input type="text" name="amount" placeholder="10"></p>
<p><button>Send</button></p>
</form>
在app.py中,/results路由是这样的:
@app.route('/results', methods=['POST'])
def process():
convert_from = request.form['convert_from']
convert_to = request.form['convert_to']
amount = request.form['amount']
c = CurrencyRates()
results = c.convert(convert_from, convert_to, amount)
return render_template("/results.html", results=results)

results。html页面是:

<p>
The converted amount is {{ results }}
</p>

当我在浏览器中运行这个时,我填写表格并点击提交以转到/results。我得到以下错误:

forex_python.converter.DecimalFloatMismatchError
forex_python.converter.DecimalFloatMismatchError: convert requires amount parameter is of type Decimal when force_decimal=True 

这很奇怪,因为我没有使用force_decimal=true。为什么会出现这个错误呢?为什么它在python中工作得很好,但在浏览器中却不行?

您的form-POST json值将是字符串类型,因为输入是字符串

@app.route('/results', methods=['POST'])
def process():
convert_from = float(request.form['convert_from'])
convert_to = float(request.form['convert_to'])
amount = float(request.form['amount'])
c = CurrencyRates()
results = c.convert(convert_from, convert_to, amount)
return render_template("/results.html", results=results)

float是将其他兼容数据类型转换为float(decimal)的内置函数。我建议将输入类型更改为number(你仍然需要float),这样用户就不会使用float函数导致错误

最新更新