在Flask中,可以通过以下步骤来实现在用户每次刷新网页时告知Flask从目录中随机获取图片:
import os
import random
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
# 获取"static"文件夹中的所有图片文件
image_files = os.listdir('static')
# 随机选择一张图片文件
random_image = random.choice(image_files)
# 构建图片文件的完整路径
image_path = os.path.join('static', random_image)
# 将图片路径传递给模板,以便在网页中显示
return render_template('index.html', image_path=image_path)
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
</head>
<body>
<img src="{{ image_path }}" alt="Random Image">
</body>
</html>
if __name__ == '__main__':
app.run()
现在,当用户每次刷新网页时,Flask应用将从"static"文件夹中随机选择一张图片,并在网页中显示出来。请注意,这里的图片路径是相对于Flask应用根目录的。
推荐的腾讯云相关产品:腾讯云对象存储(COS)。
请注意,以上答案仅供参考,具体实现方式可能因个人需求和环境而异。
领取专属 10元无门槛券
手把手带您无忧上云