我有以下代码,当我在return redirect(url_for)
和present
函数上尝试future
时,收到以下错误消息:
TypeError:home()缺少1个必需的位置参数:“ calc_type”
我尝试了多种方法将calc_type
变量传递给home
函数,并始终得到相同的错误。任何帮助表示赞赏。
from flask import render_template, redirect, url_for, request
from app import app, db
from models import Pres, Future
@app.route('/home')
def home(calc_type):
if (calc_type == "present"):
try:
inputs = Pres.query.all()
for item in inputs:
cash = item.cash
rate = item.rate
periods = item.periods
pv = cash / (1 + rate)**periods
return render_template('present.html', inputs=inputs, cash=cash, pv=pv)
except:
return render_template('present.html')
elif (calc_type == "future"):
inputs = Future.query.all()
for item in inputs:
cash = item.cash
rate = item.rate
periods = item.periods
fv = cash * (1 + rate)**periods
return render_template('present.html', inputs=inputs, cash=cash, fv=fv)
@app.route('/present', methods=['GET', 'POST'])
def present():
input = Pres(request.form['cash'], request.form['rate'], request.form['periods'])
calc_type = "present"
db.session.add(input)
db.session.commit()
return redirect(url_for('home', calc_type=calc_type))
@app.route('/future', methods=['GET', 'POST'])
def future():
input = Future(request.form['cash'], request.form['rate'], request.form['periods'])
calc_type = "future"
db.session.add(input)
db.session.commit()
return redirect(url_for('home', calc_type=calc_type))
答案 0 :(得分:0)
您以ListBox
视图的方式,无法从home()
接收参数,因为路由路径中没有这样的变量。
View函数由flask包装,并且其行为与常规函数不同。 要使主视图接收该变量,您必须在其路径路径中定义一个变量:
url_to
或者,您可以将其作为url查询变量传递:
@app.route('/home/<string:calc_type>')
def home(calc_type):
...
# Result:
>>> url_for('route', calc_type='present')
'/home/present'
但是最重要的是,您还应该尝试将视图/路由逻辑与其他代码分开,并使视图尽可能地简洁。
有两种方法可以解决此问题:
PS:我不会这样做,但它与您的代码最接近。
@app.route('/home')
def home():
calc_type = request.args.get('calc_type')
# Result:
>>> url_for('route', calc_type='present')
'/home?calc_type=present'
def get_view(calc_type):
if (calc_type == "present"):
try:
inputs = Pres.query.all()
for item in inputs:
cash = item.cash
rate = item.rate
periods = item.periods
pv = cash / (1 + rate)**periods
return render_template('present.html', inputs=inputs, cash=cash, pv=pv)
except:
return render_template('present.html')
elif (calc_type == "future"):
inputs = Future.query.all()
for item in inputs:
cash = item.cash
rate = item.rate
periods = item.periods
fv = cash * (1 + rate)**periods
return render_template('present.html', inputs=inputs, cash=cash, fv=fv)
@app.route('/present', methods=['GET', 'POST'])
def present():
input = Pres(request.form['cash'], request.form['rate'], request.form['periods'])
calc_type = "present"
db.session.add(input)
db.session.commit()
return get_view(calc_type)
@app.route('/future', methods=['GET', 'POST'])
def future():
input = Future(request.form['cash'], request.form['rate'], request.form['periods'])
calc_type = "future"
db.session.add(input)
db.session.commit()
return get_view(calc_type)