2010-05-15 79 views
1

我試圖從我的數據庫中獲取多個圖像路徑以顯示它們,但它目前不起作用。如何顯示多個圖像?

以下是我正在使用的是什麼:

def get_image(self, userid, id): 
    image = meta.Session.query(Image).filter_by(userid=userid) 
    permanent_file = open(image[id].image_path, 'rb') 
    if not os.path.exists(image.image_path): 
     return 'No such file' 
    data = permanent_file.read() 
    permanent_file.close() 
    response.content_type = guess_type(image.image_path)[0] or 'text/plain' 
    return data 

我收到有關這部分的錯誤:

image[id].image_path 

我要的是對主塔在1頁上顯示幾個jpg文件。任何想法我怎麼能實現這個?

+0

os.path.exists()檢查發生得太遲了:如果文件不存在,open()會引發IOError。使用try/except代替。 – 2010-07-07 21:54:36

回答

1

兩次使用image.image_path,但在一個地方(你告訴我們,你會犯一個錯誤),你使用image[id].image_path來代替。你認爲id可能是image的適當索引,以及爲什麼你的代碼的不同位置之間的使用差異?

如果你想要一定數量的圖像,爲什麼不使用切片語法?例如。您可以獲得前10張圖像(確保包含order_by以獲得可預測的可重複結果),您可以將filter_by的結果分割爲[0:10];第二張10張圖片,[10:20];等等。

1

我的猜測是,你假設/希望是filter_by查詢的結果包含一個字典映射檢索到他們的ID的圖像。相反,它擁有一個查詢對象,該對象表示在被強制訪問像Alex提到的切片表達式或迭代操作時返回可迭代結果集的承諾。

這可能不是解決這個問題的最好辦法,但我的猜測是,修改代碼看起來像這樣可能會完成你想要的:

def get_image(self, userid, id): 
    image = meta.Session.query(Image).filter_by(userid=userid) 
    image = dict((img.id, img) for img in image) 
    permanent_file = open(image[id].image_path, 'rb') 
    if not os.path.exists(image.image_path): 
     return 'No such file' 
    data = permanent_file.read() 
    permanent_file.close() 
    response.content_type = guess_type(image.image_path)[0] or 'text/plain' 
    return data 

更明智的方法是什麼像這樣:

def get_image(self, userid, id): 
    image = meta.Session.query(Image).filter_by(userid=userid).filter_by(id=id).first() 
    # TODO: Handle the case when image is None 
    permanent_file = open(image[id].image_path, 'rb') 
    if not os.path.exists(image.image_path): 
     return 'No such file' 
    data = permanent_file.read() 
    permanent_file.close() 
    response.content_type = guess_type(image.image_path)[0] or 'text/plain' 
    return data 

當然你要假定圖像存在匹配查詢,它可能沒有,所以你應該有一些錯誤處理爲,我離開了TODO註釋。

當然,這些更改中的任何一項都只會返回單個圖像的數據。如果你想要多個圖像,你將不得不爲每個圖像調用一次該函數,可能在請求處理程序中爲某種圖像視圖調用。

如果你確實想要一次返回多個圖像的原始圖像數據,那麼Alex的建議是使用切片來取回例如每次從數據庫中記錄10條記錄可能是最好的方法,但是您必須修改剩餘的代碼以遍歷N張圖像列表,並從文件系統中檢索每個數據並返回一些內容就像原始圖像數據blob的列表一樣。

0

假設「id」包含一個從0到多個圖像的數字,您需要先將它從一個字符串轉換爲一個int,然後才能對數組建立索引。我會做類似

 
def get_image(self, userid, id): 
    images = meta.Session.query(Image).filter_by(userid=userid) 
    try: 
     image = images[int(id)] 
     with open(image.image_path, 'rb') as f: 
      data = f.read() 
    except (IndexError, ValueError, IOError): 
     abort(404) 
    response.content_type = guess_type(image.image_path)[0] or 'application/octet-stream' 
    return data