我正在使用Python、Flask和forex_python.converter创建一个外汇货币转换器。现在,当用户在主页上提交要转换的货币和金额时,它会将他们定向到一个单独的网页,该网页仅显示其表单输入的值。最终,这将显示转换后的外汇金额。
如果用户输入了错误的外汇代码或字符串作为金额,他们将被定向回同一页面,并使用flash的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 %}
发布于 2020-10-04 12:11:37
您可以使用try catch方法来执行此操作。
try:
val = int(input())
except valueError:
try:
val = float(input())
except valueError:
#show error message发布于 2020-10-04 12:04:48
您可以使用try和except
ask_again = True
while ask_again == True:
amount = request.form.get('amount')
try:
amount = float(amount)
ask_again = False
except:
print('Enter a number')https://stackoverflow.com/questions/64191024
复制相似问题