Flask应用程序具有
static_folder返回静态文件夹的绝对路径的属性。您可以使用它来知道列出的目录,而不必将其绑定到计算机的特定文件夹结构。要为要在HTML
<img/>标签中使用的图像生成一个url
,请使用url_for(’static’,filename =’static_relative_path_to / file’)’。
import osfrom random import choicefrom 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)


