我有一个查询 sqlite 数据库的 Flask 应用程序:
@app.route('/<subject_id>')
def subject_id_lookup(subject_id):
entries = query_db('select visitdt, cvnotes from exam where id = ?',
[subject_id], one=True)
return render_template('show_results.html', entries = entries)
我使用的 Flask 函数与文档基本没有变化,包括 query_db()
def query_db(query, args=(), one = False):
"""Queries the database and returns a list of dictionaries"""
cur = g.db.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) if one else rv
最后这是我的 show_results.html 文件:
{% extends "layout.html" %}
{% block body %}
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry }}</h2>
<br>
{% else %}
<li><em>No entry here</em>
{% endfor %}
</ul>
{% endblock %}
查询运行正常,但除了变量名称 visitdt
之外没有返回任何内容。 & cvnotes
。当我将上面的行更改为 <li><h2>{{ entry.cvnotes }}</h2>
时,它什么也不返回。如何修改我的查询以显示来 self 的 subject_id_lookup()
的结果功能?
最佳答案
问题在于,query_db
返回不同的内容,具体取决于您指定的是 one=True
还是 one=False
。
>>> query_db(your_query, [some_id], one=True)
{visittd: "a value", cvnotes: "some notes"}
>>> query_db(your_query, [some_id], one=False)
[{visittd: "a value", cvnotes: "some notes"}] # Note the wrapping list
当您枚举字典时,结果是字典中的键 - 当您枚举列表时,结果是列表中的条目。
>>> for thing in query_db(your_query, [some_id], one=True):
... print thing
visitdt
cvnotes
>>> for thing in query_db(your_query, [some_id], one=False):
... print thing
{visittd: "a value", cvnotes: "some notes"}
如果您想使用相同的模板,并且您知道一个 id
只会返回一个值(或者如果您可以处理多个值),只需删除subject_id_lookup
中的 one=True
关键字参数。 entries
将是一个包含键 visitdt
和 cvnotes
的字典列表 - 当您在模板中迭代它时,每个条目都将是一个结果字典(而不是单个结果字典中的键)和 {{entry.cvnotes }}
将起作用。
关于python - 从flask调用的sqlite db仅返回变量,而不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10001712/