【问题标题】:sqlite db called from flask only returns variables, not values从烧瓶调用的 sqlite db 只返回变量,而不是值
【发布时间】:2012-04-17 14:32:19
【问题描述】:

我有一个烧瓶应用程序可以查询一个 sqlite 数据库:

@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)

我使用的烧瓶功能与包括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 %}

查询运行良好,但除了变量名visitdtcvnotes 之外什么都没有返回。当我将上面的行更改为&lt;li&gt;&lt;h2&gt;{{ entry.cvnotes }}&lt;/h2&gt; 时,它什么也不返回。如何修改查询以显示 subject_id_lookup() 函数的结果?

【问题讨论】:

    标签: python html sqlite flask


    【解决方案1】:

    问题是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 只会返回一个值(或者如果您可以处理多个值),只需删除 one=True 关键字参数在subject_id_lookupentries 将是一个包含键 visitdtcvnotes 的字典的列表 - 当您在模板中对其进行迭代时,每个条目将是一个结果字典(而不是单个结果字典中的一个键)和 @ 987654332@ 可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 2011-12-27
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多