You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask开发外汇转换器遇TypeError:float()参数为NoneType问题排查

问题:Flask外汇转换应用中request.form.get()获取amount值为None导致报错

错误信息

Traceback (most recent call last):
  File "/home/sam/Forex Converter/Converter!/venv/lib/python3.10/site-packages/flask/app.py", line 2213, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/sam/Forex Converter/Converter!/venv/lib/python3.10/site-packages/flask/app.py", line 2193, in wsgi_app
    response = self.handle_exception(e)
  File "/home/sam/Forex Converter/Converter!/venv/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/sam/Forex Converter/Converter!/venv/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/sam/Forex Converter/Converter!/venv/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/sam/Forex Converter/Converter!/venv/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/sam/Forex Converter/Converter!/app.py", line 45, in convert_page
    final_curr = currency.convert(from_curr, to_curr, amount)
  File "/home/sam/Forex Converter/Converter!/venv/lib/python3.10/site-packages/forex_python/converter.py", line 90, in convert
    return float(amount)
TypeError: float() argument must be a string or a real number, not 'NoneType'

现有代码

Python代码

from flask import Flask, request, render_template, redirect, session, url_for
from forex_python.converter import CurrencyRates

app = Flask(__name__)
app.config.update(
    TESTING=True,
    SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
)
currency = CurrencyRates()

@app.route('/')
def index():
    """Show homepage."""
    session['count'] = session.get('count', 0) + 1
    return render_template("body.html")

@app.route('/convert', methods=['GET','POST'])
def convert_page():
    """Shows conversion area"""
    amount = request.form.get('amount')
    from_curr = request.form.get('from_curr')
    to_curr = request.form.get('to_curr')

    final_curr = currency.convert(from_curr, to_curr, amount)
    return render_template("convert.html", display_result=final_curr)

HTML代码

<h1> Convert your coins here!!</h1>

<h2>Conversion</h2>

<form action="{{url_for('convert_page') }}" method="post">
    <input type="text" placeholder="Enter amount" id="amount"><br>
    <br>
    <input type="text" placeholder="From currency" id="from_curr"><br>
    <br>
    <input type="text" placeholder="To currency" id="to_curr">
    <button type="submit">Submit!</button>
</form>

<p id="result_paragraph">{{ display_result }}</p>

尝试过的方法

  • 直接将amount转为整数:amount = int(request.form.get('amount')),仍报错
  • 使用try-catch捕获异常,无效

疑问与需求

  • 疑惑:request.args获取的值应为字符串,为何会出现None?
  • 需求:获取用户输入的数值(整数)用于汇率计算,该逻辑在控制台运行正常,但Flask中出错

解决方案

1. 核心问题修复:HTML输入元素缺少name属性

Flask的request.form是通过表单元素的name属性获取值,而非id。你的三个输入框仅设置了id,没有name,导致表单提交时字段未被发送到后端,所以request.form.get()返回None。

修改HTML表单,给每个输入框添加name属性(与id保持一致即可):

<form action="{{url_for('convert_page') }}" method="post">
    <input type="text" placeholder="Enter amount" id="amount" name="amount"><br>
    <br>
    <input type="text" placeholder="From currency" id="from_curr" name="from_curr"><br>
    <br>
    <input type="text" placeholder="To currency" id="to_curr" name="to_curr">
    <button type="submit">Submit!</button>
</form>

2. 额外优化:参数校验与异常处理

即使修复了name属性,仍需处理用户输入不合法的情况(如非数字、空值、无效货币代码等),避免程序崩溃:

@app.route('/convert', methods=['GET','POST'])
def convert_page():
    """Shows conversion area"""
    if request.method == 'POST':
        amount = request.form.get('amount')
        from_curr = request.form.get('from_curr', '').upper()
        to_curr = request.form.get('to_curr', '').upper()
        
        error = None
        # 校验必填字段
        if not amount or not from_curr or not to_curr:
            error = "请填写所有字段"
        else:
            try:
                # 转换金额为浮点数
                amount_float = float(amount)
                final_curr = currency.convert(from_curr, to_curr, amount_float)
                return render_template("convert.html", display_result=final_curr, error=error)
            except ValueError:
                error = "金额必须是有效数字"
            except Exception as e:
                error = f"转换失败:{str(e)}"
        
        return render_template("convert.html", error=error)
    
    # GET请求直接返回页面
    return render_template("convert.html")

同时在HTML中添加错误提示:

{% if error %}
<p style="color: red;">{{ error }}</p>
{% endif %}
<p id="result_paragraph">{{ display_result }}</p>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:35:02