如何使用 Flask 返回列表 [英] How to return a list with Flask
问题描述
我正在尝试构建一个网页,其中包含存储在我的数据库中的调查问题和答案.我从我的数据库中获得了两个单独列表中的问题和答案,我想返回它们(将它们相互组合),但我收到了这个错误列表对象不可调用".代码是:
I'm trying to build a web page with questions and answers of a survey stored in my database. I get from my database the questions and answers in two separate lists and I'd like to return them (combining them each other) but I received this error "list object is not callable". The code is:
@app.route('/show/<quest>')
def show(quest):
q_id = g.db.execute("SELECT id_survey FROM surveys WHERE survey=?",[quest]).fetchone()[0]
a = g.db.execute("SELECT q_id,a_id FROM mesh WHERE s_id=? ORDER BY q_id",[q_id]).fetchall()
questions=list()
answers=list()
for i in a:
b = g.db.execute("SELECT question FROM questions WHERE id_questions=?",[i[0]]).fetchone()[0]
c = g.db.execute("SELECT answer FROM answers WHERE id_aswers=?",[i[1]]).fetchone()[0]
domande.append(b)
risposte.append(c)
return domande + answers
理想的结果应该是:
调查标题
问题 1:答案
问题 2:答案
...
等等
P.S.:例如2个列表的问题和答案是这样的:
P.S.: For example the 2 lists questions and answers are like this:
questions=[你最喜欢的颜色?',你最喜欢的颜色?',你最喜欢的颜色?',你喜欢意大利面吗?',你喜欢意大利面吗?']
questions=[u'favourite color?',u'favourite color?',u'favourite color?',u'do you like pasta?',u'do you like pasta?']
answers=[u'red',u'green',u'blue',u'yes',u'no']
answers=[u'red',u'green',u'blue',u'yes',u'no']
它们总是具有相同的长度.提前致谢.
They always have the same length. Thank you in advance.
推荐答案
试试这个:
@app.route('/show-quest')
def showquestion():
questions = ['favourite color?','favourite color?','favourite color?','do you like pasta?','do you like pasta?']
answers = ["red","green",'blue','yes','no']
return render_template('question.html', questions=questions, answers=answers)
问题.html
{% for question in questions %}
<p>{{question[0]}}</p>
{% for answer in answers[0:3] %}
<p>{{answer}}</p>
{% endfor %}
{% endfor %}
这篇关于如何使用 Flask 返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!