2014-09-26 44 views
2
def get_path(): 
    imgs = [] 

    for img in os.listdir('/Users/MYUSERNAME/Desktop/app/static/imgs/'): 
     imgs.append(img) 
    image = random.randint(0, len(imgs)-1) #gen random image path from images in directory 
    return imgs[image].split(".")[0] #get filename without extension 

@app.route("/blahblah") 
def show_blah(): 
    img = get_path() 
    return render_template('blahblah.html', img=img) #template just shows image 

我想要做的是不必使用操作系統獲取文件,除非有辦法使用燒瓶方法。我知道這種方式只適用於我的電腦,而不是我嘗試上傳的任何服務器。如何列出Flask靜態子目錄中的所有圖像文件?

回答

2

Flask應用程序有一個屬性static_folder,它返回靜態文件夾的絕對路徑。您可以使用它來知道要列出的目錄,而無需將其綁定到計算機的特定文件夾結構。要爲HTML <img/>標籤中的圖像生成url,請使用`url_for('static',filename ='static_relative_path_to/file')'。

import os 
from random import choice 
from flask import url_for, render_template 


@app.route('/random_image') 
def random_image(): 
    names = os.listdir(os.path.join(app.static_folder, 'imgs')) 
    img_url = url_for('static', filename=os.path.join('imgs', choice(names))) 

    return render_template('random_image.html', img_url=img_url) 
相關問題