2017-03-18 88 views
0

我正在試驗Pyrebase,試圖從Firebase中提取一些數據並將它們呈現在燒瓶中。這是我的數據怎麼看起來火力database screenshot蟒蛇 - 如何在燒瓶中呈現Firebase字典

在燒瓶蟒蛇,檢索數據並傳遞給render_template這樣的:

@app.route('/') 
def home(): 
all_post = db.child("post").get().val() 
for i, (key, value) in enumerate(all_post.items()): 
    dict = value 
    print(dict) 
return render_template('home.html', post=dict) 

此時,字典看起來像這樣從上面

print語句
{'postTitle': 'Second title', 'postBody': 'Second tyext'} 
{'postTitle': 'Title of my post', 'postBody': 'Body of my post'} 

在我的瓶/神社模板,我的循環字典試圖使這就像一個博客帖子,在那裏我想顯示每個博客的標題數據和它的數據庫中的正文

{% for key, value in dict.items() %} 
      <h2>{{ key }}</h2> 
      <P>{{ value }}</P> 
    {% endfor %} 

試圖使像上面時,我得到的錯誤給出:

TypeError: descriptor 'items' of 'dict' object needs an argument 

什麼是去它的最好辦法,還是我哪裏出了錯?

回答

2

TypeError: descriptor 'items' of 'dict' object needs an argument

錯誤是因爲您正在嘗試執行dict.items()。如試圖在內置字典數據結構上調用items()而不是您創建的名稱。問題是在模板中dict未被稱爲dict。它在模板中被稱爲post

如果你看一看:

render_template('home.html', post=dict) 

你說post=dict。因此改變:

{% for key, value in dict.items() %} 

分爲:

{% for key, value in post.items() %} 

however it rendered just one post and I have two post in the database

那是因爲你通過帖子循環,始終分配電流崗位dict。所以你總是會看到最後的帖子。

相反,你可以做這樣的事情:

posts = [] 
for i, (key, value) in enumerate(all_post.items()): 
    posts.append(value) 
    print(value) 
return render_template('home.html', posts=posts) 
{% for post in posts %} 
    {% for key, value in post.items() %} 
     <h2>{{ key }}</h2> 
     <P>{{ value }}</P> 
    {% endfor %} 
{% endfor %} 
+0

謝謝了,這是一個愚蠢的,我改post.items(),但是它呈現的只是一個職位,我有兩個交在數據庫中。 – joke4me

+0

@ joke4me看看我的更新。 – Vallentin

+0

我的循環仍然不正確我想,請你看看請 – joke4me