
本教程详细介绍了如何在python flask应用中实现图片的动态展示与定时刷新。内容涵盖flask后端正确配置图片路径、html模板中利用`url_for`显示图片,以及通过javascript实现前端图片的周期性更新。此外,还提供了处理图片上传以动态替换图片内容的完整示例,并强调了相关最佳实践。
在Web应用中,动态展示和定时刷新图片是一个常见的需求,例如显示实时图表、监控画面或轮播图。本教程将指导您如何在Python Flask框架下,结合HTML和JavaScript实现这一功能。
首先,我们需要在Flask应用中配置一个静态文件夹来存放图片,并通过路由将其渲染到HTML模板中。
1.1 Flask 应用配置 (app.py)
创建一个app.py文件,并设置静态文件路径。为了更好地组织项目,我们通常会将图片存放在static/images目录下。
import os
from flask import Flask, render_template, url_for, flash, request, redirect
from werkzeug.utils import secure_filename
# 配置上传文件夹和允许的文件扩展名
UPLOAD_FOLDER = os.path.join('static', 'images')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Flash消息需要一个密钥
app.secret_key = 'your_secret_key_here' # 生产环境请使用复杂且安全的密钥
# 辅助函数:检查文件扩展名是否允许
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/")
def index():
return "<p>Flask应用正在运行!</p>"
@app.route("/chart")
def show_img():
# 假设我们总是显示名为 'chart.png' 的图片
image_path_in_static = os.path.join('images', 'chart.png')
# 检查图片是否存在,如果不存在可以显示一个占位符或错误图片
full_image_path = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], 'chart.png')
if not os.path.exists(full_image_path):
image_path_in_static = 'images/placeholder.png' # 假设有一个占位符图片
flash('图片 chart.png 不存在,请先上传!', 'error')
return render_template("chart.html", user_image=image_path_in_static)
if __name__ == "__main__":
# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.run(port=3000, debug=True)代码说明:
1.2 HTML 模板 (templates/chart.html)
在templates目录下创建chart.html文件,用于显示图片。
<!DOCTYPE html>
<html>
<head>
<title>动态图片展示</title>
<style>
img { max-width: 100%; height: auto; display: block; margin-top: 20px; border: 1px solid #ddd; }
.flash { color: green; font-weight: bold; }
.error { color: red; font-weight: bold; }
.flash-messages { list-style: none; padding: 0; }
</style>
</head>
<body>
<h1>图片展示</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class="flash-messages">
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<img src="{{ url_for('static', filename=user_image) }}" alt="动态图片">
</body>
</html>模板说明:
悟空CRM是一种客户关系管理系统软件.它适应Windows、linux等多种操作系统,支持Apache、Nginx、IIs多种服务器软件。悟空CRM致力于为促进中小企业的发展做出更好更实用的软件,采用免费开源的方式,分享技术与经验。 悟空CRM 0.5.5 更新日志:2017-04-21 1.修复了几处安全隐患; 2.解决了任务.日程描述显示问题; 3.自定义字段添加时自动生成字段名
284
要实现图片的定时刷新,我们需要在前端(chart.html)使用JavaScript。关键在于定时更新<img>标签的src属性。为了强制浏览器重新加载图片而不是使用缓存,我们通常会在URL后添加一个时间戳或随机查询参数。
2.1 修改 chart.html 添加 JavaScript
在chart.html中添加<script>标签:
<!DOCTYPE html>
<html>
<head>
<title>动态图片展示与刷新</title>
<style>
img { max-width: 100%; height: auto; display: block; margin-top: 20px; border: 1px solid #ddd; }
.flash { color: green; font-weight: bold; }
.error { color: red; font-weight: bold; }
.flash-messages { list-style: none; padding: 0; }
</style>
</head>
<body>
<h1>图片动态展示与刷新</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class="flash-messages">
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<h2>当前图片 (<span id="refresh-counter">每5秒刷新</span>)</h2>
<img id="dynamic-image" src="{{ url_for('static', filename=user_image) }}" alt="动态图片">
<script>
document.addEventListener('DOMContentLoaded', function() {
const imgElement = document.getElementById('dynamic-image');
const refreshCounter = document.getElementById('refresh-counter');
let countdown = 5; // 刷新倒计时,与 setInterval 间隔一致
function updateImage() {
// 获取当前图片的原始URL(不带查询参数)
const currentSrc = imgElement.src.split('?')[0];
// 添加一个时间戳作为查询参数,强制浏览器刷新缓存
imgElement.src = currentSrc + '?' + new Date().getTime();
console.log('图片已刷新:', imgElement.src);
countdown = 5; // 刷新后重置倒计时
refreshCounter.textContent = `每${countdown}秒刷新`;
}
// 初始化倒计时显示
refreshCounter.textContent = `每${countdown}秒刷新`;
// 每秒更新倒计时,每5秒刷新图片
setInterval(function() {
countdown--;
if (countdown <= 0) {
updateImage(); // 执行图片刷新
} else {
refreshCounter.textContent = `每${countdown}秒刷新`;
}
}, 1000); // 每1000毫秒(1秒)执行一次
});
</script>
</body>
</html>JavaScript 代码说明:
为了让“图片本身变化但文件名不变”的需求有实际意义,我们需要一种机制来更新服务器上的图片文件。这里我们通过一个文件上传功能来实现。
3.1 修改 app.py 添加上传路由
在app.py中添加一个文件上传路由:
import os
from flask import Flask, render_template, url_for, flash, request, redirect
from werkzeug.utils import secure_filename
# 配置上传文件夹和允许的文件扩展名
UPLOAD_FOLDER = os.path.join('static', 'images')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'your_secret_key_here' # 生产环境请使用复杂且安全的密钥
# 辅助函数:检查文件扩展名是否允许
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/")
def index():
return "<p>Flask应用正在运行!</p>"
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# 检查请求中是否有文件部分
if 'file' not in request.files:
flash('未选择文件', 'error')
return redirect(request.url)
file = request.files['file']
# 如果用户没有选择文件,浏览器会提交一个空文件
if file.filename == '':
flash('未选择文件', 'error')
return redirect(request.url)
if file and allowed_file(file.filename):
# 将上传的文件保存为固定名称 'chart.png',会覆盖旧文件
filename_to_save = 'chart.png'
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename_to_save))
flash('图片上传成功并已更新!', 'success')
return redirect(url_for('show_img')) # 上传成功后重定向回图片展示页
# 如果是GET请求,或者上传失败,可以渲染一个上传表单页面
# 但在此示例中,我们直接在 chart.html 中包含上传表单
return redirect(url_for('show_img'))
@app.route("/chart")
def show_img():以上就是Flask应用中实现动态图片展示与定时刷新的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号