You need to enable JavaScript to run this app. 使用Flask搭配forex-python开发货币转换器报DecimalFloatMismatchError排查
优惠活动
大模型
产品
解决方案
定价
更多

使用Flask搭配forex-python开发货币转换器报DecimalFloatMismatchError排查

问题根因

你遇到的报错本质是前后端数据类型不匹配,和你有没有手动设置force_decimal=True没有直接关系:

  • 在ipython测试环境中,调用c.convert('USD', 'EUR', 10)时传入的10是Python原生整数类型,完全符合库的入参要求,可以正常运行
  • 在Flask表单场景中,通过request.form取到的所有表单值,不管前端输入框填的是数字还是字母,后端拿到的都是字符串类型,也就是实际传给c.convert的amount值是"10"这类字符串
  • 查看forex-python的内部逻辑,当检测到传入的amount参数既不是int、float类型也不是Decimal类型时,库会自动触发强制十进制校验模式,此时要求传入的amount必须是Decimal实例,否则就会抛出DecimalFloatMismatchError——这就是你没有手动开启force_decimal却依然触发校验的原因。
附带发现的代码问题
  • 路由代码存在缩进错误:c = CurrencyRates()、后续的转换、render_template语句都没有缩进到process()函数内部,会导致代码运行时作用域异常
  • 模板路径书写错误:render_template("/results.html")前面的斜杠会让Flask从系统根目录查找模板文件,去掉斜杠改成render_template("results.html"),才会从默认的templates目录加载模板
  • 货币代码格式不兼容:用户在前端输入框填的货币代码可能是小写,而forex-python默认识别大写的ISO标准货币代码,不做格式转换可能出现识别失败
可直接运行的修复代码
from flask import Flask, render_template, request
from forex_python.converter import CurrencyRates
from decimal import Decimal

app = Flask(__name__)

# 新增首页路由加载表单页
@app.route('/')
def index():
    return render_template("index.html")

@app.route('/results', methods=['POST'])
def process():
    # 去除输入前后空格,统一转大写匹配货币代码格式
    convert_from = request.form['convert_from'].strip().upper()
    convert_to = request.form['convert_to'].strip().upper()
    # 将字符串类型的金额转为Decimal,匹配库的校验要求
    amount = Decimal(request.form['amount'])

    c = CurrencyRates()
    results = c.convert(convert_from, convert_to, amount)
    return render_template("results.html", results=results)

if __name__ == '__main__':
    app.run(debug=True)

补充说明:如果不想引入Decimal做转换,也可以把金额转为float类型,即写为amount = float(request.form['amount']),这种类型也符合forex-python的入参要求,不会触发强制十进制校验。

内容的提问来源于stack exchange,提问作者user7876451

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.03 10:45:04