我试图将在一条路线(/index
)上生成的对象传递给另一条路线(/ello
),这样我就不必进行重复查询。
在/index
路线...
@app.route('/',methods=['GET'])
def index(x=None,y=None):
persons = Person.query.filter(Person.id != current_user_person_id).all()
person1 = random.choice(persons)
person2 = random.choice(persons)
x,y = pair_generator(person1,person2)
return render_template('index.html',x=x,y=y)
...并在/ello
路线上操纵:
@app.route('/ello',methods=['POST'])
def ello():
winner_id = int(request.form['winner_id'])
winner_score = int(request.form['winner_score'])
loser_id = int(request.form['loser_id'])
loser_score = int(request.form['loser_score'])
# ELO CALCULATIONS GO HERE; OMITTED FOR BREVITY
winner_object = Person.query.filter_by(id=winner_id).first()
loser_object = Person.query.filter_by(id=loser_id).first()
db.session.commit()
return redirect(url_for('index'))
以下是index.html
的相关部分:
<form action="{{url_for('ello')}}" method="post">
<input type="submit" name="nickname" value="{{x.nickname}}" />
<input type="hidden" name="winner_id" value="{{x.id}}" />
<input type="hidden" name="winner_score" value="{{x.score}}" />
<input type="hidden" name="loser_id" value="{{y.id}}" />
<input type="hidden" name="loser_score" value="{{y.score}}" />
</form>
<form action="{{url_for('ello')}}" method="post">
<input type="submit" name="nickname" value="{{y.nickname}}" />
<input type="hidden" name="winner_id" value="{{y.id}}" />
<input type="hidden" name="winner_score" value="{{y.score}}" />
<input type="hidden" name="loser_id" value="{{x.id}}" />
<input type="hidden" name="loser_score" value="{{x.score}}" />
</form>
如您所见,我正在查询Person表两次。是否可以在路由之间传递对象? (或者&#34;坚持&#34;他们以某种方式?)这样,我可以允许/ello
路由访问和操作在/index
中创建的两个Person对象。
真的,我希望能够做到这样的事情:
<form action="{{url_for('ello', winner_object=x, loser_object=y)}}" method="post">
<input type="submit" value="{{x.nickname}}" />
</form>
<form action="{{url_for('ello', winner_object=y, loser_object=x)}}" method="post"
<input type="submit" value="{{y.nickname}}" />
</form>
...但这当然会传递字符串,而不是对象:
http://127.0.0.1:5000/ello?
winner_object=<app.Person+object+at+0x1062b1290>&loser_object=<app.Person+object+at+0x1062b1490>
答案 0 :(得分:0)
我遇到了类似的问题,无法确定正确的方法,因此创建了一个会话,然后在每个页面上都可以使用此变量。