【问题标题】:Python currency converter - how to handle the amount being emptyPython货币转换器 - 如何处理金额为空
【发布时间】:2021-05-21 18:24:52
【问题描述】:

我用 Python/Flask 构建了一个非常简单的货币转换器。我正在使用一个名为forex-python 的库。一切正常,但是当用户将“金额”留空时应用程序崩溃,并且我收到 Python 错误ValueError: could not convert string to float:

我有try.. except 用于ValueErrorTypeError,但它们不起作用。我猜,当用户将“金额”留空时,它会被视为字符串,python 无法将其转换为float

那么我该如何优雅地处理这个问题呢?我只是想将用户重定向到'/' 并向他们显示一条消息。

代码如下:

@app.route('/results', methods=['POST'])
def process():
    conv_from = request.form['conv_from']
    conv_to = request.form['conv_to']
    amount = float(request.form['amount'])
    
    rates = CurrencyRates()
    codes = CurrencyCodes()
    
    try:
        results = round(rates.convert(conv_from, conv_to, amount), 2)
        symbol = codes.get_symbol(conv_to)
        return render_template("/results.html", conv_from=conv_from, conv_to=conv_to, amount=amount, results=results, symbol=symbol)
    except RatesNotAvailableError:
        flash("Please enter a valid currency")
        return redirect('/')
    except (ValueError, TypeError):
        flash("Oops something went wrong")
        return redirect('/')

【问题讨论】:

  • 您可以改用amount = request.form.get('amount', type=float),它不会引发异常,但如果它不存在,它将返回None。然后你可以像if amount is None: ....这样检查

标签: python flask


【解决方案1】:

一个简单的if 语句来检查字符串是否为空就足够了:

@app.route('/results', methods=['POST'])
def process():
    conv_from = request.form['conv_from']
    conv_to = request.form['conv_to']
    if request.form['amount'] == "":
        print("Enter a valid amount")
        return False
    else:
        amount = float(request.form['amount'])
    
    rates = CurrencyRates()
    codes = CurrencyCodes()
    
    try:
        results = round(rates.convert(conv_from, conv_to, amount), 2)
        symbol = codes.get_symbol(conv_to)
        return render_template("/results.html", conv_from=conv_from, conv_to=conv_to, amount=amount, results=results, symbol=symbol)
    except RatesNotAvailableError:
        flash("Please enter a valid currency")
        return redirect('/')
    except (ValueError, TypeError):
        flash("Oops something went wrong")
        return redirect('/')

但是,这只检查字符串是否为空。如果我尝试输入 5 USD 但输入 5xyz 将无法处理。在这种情况下,像这样的 try/catch 块也可以工作。

@app.route('/results', methods=['POST'])
def process():
    conv_from = request.form['conv_from']
    conv_to = request.form['conv_to']
    try:
        amount = float(request.form['amount'])
    except:
        print("Not a valid amount")
    rates = CurrencyRates()
    codes = CurrencyCodes()
    try:
        results = round(rates.convert(conv_from, conv_to, amount), 2)
        symbol = codes.get_symbol(conv_to)
        return render_template("/results.html", conv_from=conv_from, conv_to=conv_to, amount=amount, results=results, symbol=symbol)
    except RatesNotAvailableError:
        flash("Please enter a valid currency")
        return redirect('/')
    except (ValueError, TypeError):
        flash("Oops something went wrong")
        return redirect('/')

【讨论】:

    【解决方案2】:

    您没有在 try/except 块中进行投射。只需更改amount 变量的位置(您使用float 方法对其进行转换的位置),使其位于try/except 块中,并且应该处理异常。

    所以解决方法是:

    @app.route('/results', methods=['POST'])
    def process():
        conv_from = request.form['conv_from']
        conv_to = request.form['conv_to']
        
        rates = CurrencyRates()
        codes = CurrencyCodes()
        
        try:
            amount = float(request.form['amount'])
            results = round(rates.convert(conv_from, conv_to, amount), 2)
            symbol = codes.get_symbol(conv_to)
            return render_template("/results.html", conv_from=conv_from, conv_to=conv_to, amount=amount, results=results, symbol=symbol)
        except RatesNotAvailableError:
            flash("Please enter a valid currency")
            return redirect('/')
        except ValueError:
            flash("Invalid amount provided!")
            return redirect('/')
        except TypeError:
            flash("Oops something went wrong")
            return redirect('/')
    

    【讨论】:

      【解决方案3】:

      我认为这将是最干净的解决方案,如果您愿意,您也可以将 request.form.get() 用于您的其他 request.form 变量。

      如果指定的键不存在或变量类型与request.form.get() 中指定的type 不匹配,则request.form.get() 返回None

      Python 代码:

      @app.route('/results', methods=['POST'])
      def process():
          conv_from = request.form['conv_from']
          conv_to = request.form['conv_to']
          amount = request.form.get('amount', type=float)
      
          if amount is None:
              flash('Please enter a valid amount!')
              return redirect('/')
          
          rates = CurrencyRates()
          codes = CurrencyCodes()
          
          try:
              results = round(rates.convert(conv_from, conv_to, amount), 2)
              symbol = codes.get_symbol(conv_to)
              return render_template("/results.html", conv_from=conv_from, conv_to=conv_to, amount=amount, results=results, symbol=symbol)
          except RatesNotAvailableError:
              flash("Please enter a valid currency")
              return redirect('/')
          except (ValueError, TypeError):
              flash("Oops something went wrong")
              return redirect('/')
      

      【讨论】:

        猜你喜欢
        • 2021-03-15
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多