我正在尝试构建预算网络应用程序,主要用于实践,但是我也希望它成为我的主要预算工具。我不太擅长Python,但我想成为。
我度过了一段艰难的时期,这就是为什么我转向你们。
这是我的budget.py
代码:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def entry():
return render_template('entry.html',
the_title='Smith Family Budgeting')
@app.route('/income', methods=['POST', 'GET'])
def income():
return render_template('income.html')
@app.route('/housing', methods=['POST', 'GET'])
def results():
if request.method == 'POST':
income = request.form["income"]
return render_template('housing.html', the_income = income)
@app.route('/transportation', methods=['POST', 'GET'])
def transport():
if request.method == 'POST':
income = request.form["income"]
mortgage = request.form['housing']
leftover = int(income) - int(mortgage)
return render_template('trans.html', leftover=leftover)
app.run(debug = True)
html for housing.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Allocating for housing</title>
</head>
<body>
<p>You have ${{ the_income }} left to spend!</p>
<form action="/transportation">
<p>How much is the mortgage this month?</p>
<input name="housing" type="TEXT">
<p>Next up: Transportation</p>
<input type="SUBMIT" value="Next">
</form>
<form action="/income">
<input type="SUBMIT" value="Back">
</form>
</body>
</html>
从外观上您可能会看到,用户通过输入每个类别的数据来浏览应用程序。我想保持剩余预算的不断增长,但我正努力超越第一部分。
flask调用/ transportation页时,出现“ TypeError:view函数未返回有效响应。该函数返回None或不返回return语句而结束。”
我不确定为什么会这样,尽管我怀疑这与“剩余”变量有关。我怀疑也许减去两个不同表单数据的值不是解决此问题的正确方法,但我不确定是什么。欢迎任何建议!
我可以发布模板,尽管我不确定解决这些模板是否需要它们。非常感谢你们,我真的很高兴这个资源存在。
答案 0 :(得分:0)
使用session
将数据传递到下一条路线,并在用户返回到收入页面时清除会话
将url_for
用于表格action
在budget.py
from flask import Flask, render_template, request, session
app = Flask(__name__)
app.secret_key = "super_secret_key"
@app.route('/', methods=['GET'])
def entry():
return render_template('entry.html',
the_title='Smith Family Budgeting')
@app.route('/income', methods=['GET'])
def income():
session['income'] = ''
return render_template('income.html')
@app.route('/housing', methods=['POST'])
def results():
if request.method == 'POST':
session['income'] = request.form["income"]
return render_template('housing.html', the_income=session['income'])
@app.route('/transportation', methods=['POST'])
def transport():
if request.method == 'POST':
income = session["income"]
mortgage = request.form['housing']
leftover = int(income) - int(mortgage)
return render_template('trans.html', leftover=leftover)
app.run(debug = True)
在housing.html
中编辑表格action
和method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Allocating for housing</title>
</head>
<body>
<p>You have ${{ the_income }} left to spend!</p>
<form action="{{ url_for('transport') }}" method="POST">
<p>How much is the mortgage this month?</p>
<input name="housing" type="TEXT">
<p>Next up: Transportation</p>
<input type="SUBMIT" value="Next">
</form>
<form action="{{ url_for('income') }}">
<input type="SUBMIT" value="Back">
</form>
</body>
</html>