您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何列出Flask静态子目录中的所有图像文件?

如何列出Flask静态子目录中的所有图像文件?

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)
Python 2022/1/1 18:41:41 有274人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶