简体   繁体   中英

Python currency converter Decimal Float Mismatch Error

I'm trying to build a very simple currency converter with Python/Flask. I'm using a library called forex-python . When I try this in the command line using ipython. Everything works great:

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

Great, But when I try this by running a flask server and doing it in the browser. it doesn't work. My form in index:html looks like this:

<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>

And in app.py, the /results route looks like this:

@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)

And then the results.html page is simply:

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

When I run this in the browser, I fill the form and hit submit to go to /results. I get the following error:

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

This is odd, because I'm not using force_decimal=true. So why is this error happening? And why does it work fine in ipython, but not in the browser?

Your form-POST json values will be of type string since inputs give strings

@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 is a builtin to convert other compatible data-types to float(Decimals) and I would recommend changing the input type to number(U still need float) so that the user cant cause errors with the float function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM