2012-04-03 52 views
2

我具有長頸瓶的應用程序,查詢一個SQLite數據庫:從燒瓶稱爲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 %} 

查詢運行正常但除了變量名稱visitdt & cvnotes之外沒有任何東西被返回。當我將上面的行更改爲<li><h2>{{ entry.cvnotes }}</h2>時,它不返回任何內容。如何修改我的查詢以顯示我的subject_id_lookup()函數的結果?

回答

3

問題是,query_db返回不同的事情取決於您是否指定one=Trueone=False

​​

當您枚舉字典的結果是字典中的鍵 - 當你枚舉列表,其結果是在列表中的條目。

>>> 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_lookup。然後entries將成爲包含密鑰visitdtcvnotes的一個字典的列表 - 當您在模板中遍歷它時,每個條目將是結果字典(而不是單個結果字典中的密鑰),並且{{ entry.cvnotes }}將起作用。

相關問題