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)