如何在不接收错误的情况下将用户表单输入转换为整数或浮点?

2024-06-11 20:48:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python、Flask和forex_Python.converter创建一个外汇货币转换器。现在,当用户在主页上提交要转换的货币和金额时,它会将他们引导到一个单独的网页,只显示其表单输入的值。最终,这将显示已转换的外汇金额

如果用户输入不正确的外汇代码或字符串作为金额,他们将被引导回同一页面,错误横幅将使用Flasks的flash消息显示。我已经能够成功地为不正确的外汇代码输入创建错误横幅,但是我正在努力为无效金额创建一个错误横幅。理想情况下,如果用户输入的“金额”是字母、空白或符号而不是数字,则横幅将显示“无效金额”。此时,横幅将始终显示,但用户金额永远不会转换为浮动

我尝试使用float()将用户输入的金额转换为浮点值,当金额为整数(或浮点值)时,该操作成功,但是如果输入是其他内容,则会收到错误,代码停止。我已经被这个问题困扰了好几个小时了,所以如果有人对如何解决这个问题有任何策略,我将不胜感激

我的python代码和3个HTML页面如下:

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

app = Flask(__name__)
app.config['SECRET_KEY'] = "secretkey"

# store all currency rates into variable as a dictionary
c = CurrencyRates()
fx_rates = c.get_rates('USD')

# home page
@app.route('/', methods=['POST', 'GET'])
def home():
    return render_template('home.html')

# result page. User only arrives to result.html if inputs info correctly
@app.route('/result', methods=['POST', 'GET'])
def result():
    # grab form information from user and change characters to uppercase
    forex_from = (request.form.get('forex_from').upper())
    forex_to = (request.form.get('forex_to').upper())

    # Where I am running into issues.
    # I have tried:      
    #      before_amount = (request.form.get('amount').upper())
    #             amount = float(before_amount)
    amount = request.form.get('amount')
    print(amount)

    # if input is invalid bring up banner error
    if forex_from not in fx_rates :
        flash(f"Not a valid code: {forex_from}")
    
    if forex_to not in fx_rates :
        flash(f"Not a valid code: {forex_to}")

    if not isinstance(amount, float) :
        flash("Not a valid amount.")

    # if any of above errors occur, direct to home, else direct to result.html
    if forex_to not in fx_rates or forex_from not in fx_rates or not isinstance(amount, float):
        return redirect(url_for('home'))
    else :
        return render_template('result.html', forex_from=forex_from, forex_to=forex_to, amount=amount)

<!-- Base.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous"> <title>Forex Converter!</title> </head> <body> {% block content %} {% endblock %} </body> </html>

<!-- home.html --> {% extends "base.html" %} {% block content %} <h1>Forex Converter!</h1> {% for msg in get_flashed_messages() %} <div class="alert alert-danger" role="alert"> <h3>{{msg}}</h3> </div> {% endfor %} <div class="alert alert-danger d-none" role="alert"> Not a valid amount. </div> <form action="/result" method="POST"> <div class="form-group"> <label for="forex_from">Converting from</label> <input name="forex_from" type="text"><br> </div> <div class="form-group"> <label for="forex_to">Converting to</label> <input name="forex_to" type="text"> <br> </div> <div class="form-group"> <label for="amount">Amount: </label> <input name="amount" type="text"><br> </div> <button type="submit" class="btn btn-primary">Convert</button> </form> {% endblock %}

<!-- result.html --> {% extends "base.html" %} {% block content %} <h1>Forex Converter!</h1> <h3>forex_from: {{forex_from}}</h3> <h3>forex_to: {{forex_to}}</h3> <h3>amount: {{amount}}</h3> <form action="/"> <button type="submit" class="btn btn-primary">Home</button> </form> {% endblock %}

Tags: tofromdivformforgetifhtml
2条回答

您可以使用tryexcept

ask_again = True
while ask_again == True:
    amount = request.form.get('amount')
    try:
        amount = float(amount)
        ask_again = False
    except:
        print('Enter a number')

您可以使用try-catch方法来执行此操作

try:
    val = int(input())
except valueError:
    try:
         val = float(input())
    except valueError:
          #show error message

相关问题 更多 >