Flask应用中实现动态图片展示与定时刷新

霞舞
发布: 2025-12-02 08:03:30
原创
940人浏览过

Flask应用中实现动态图片展示与定时刷新

本教程详细介绍了如何在python flask应用中实现图片的动态展示与定时刷新。内容涵盖flask后端正确配置图片路径、html模板中利用`url_for`显示图片,以及通过javascript实现前端图片的周期性更新。此外,还提供了处理图片上传以动态替换图片内容的完整示例,并强调了相关最佳实践。

在Web应用中,动态展示和定时刷新图片是一个常见的需求,例如显示实时图表、监控画面或轮播图。本教程将指导您如何在Python Flask框架下,结合HTML和JavaScript实现这一功能。

1. Flask 应用中基础图片展示

首先,我们需要在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)
登录后复制

代码说明:

  • app.config['UPLOAD_FOLDER']:定义了图片上传的目录,这里指向static/images。
  • @app.route("/chart"):定义了一个路由,当访问/chart时,会渲染chart.html模板。
  • render_template("chart.html", user_image=image_path_in_static):将图片在static目录下的相对路径image_path_in_static传递给模板。
  • os.makedirs(UPLOAD_FOLDER, exist_ok=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 v 0.5.5
悟空CRM v 0.5.5

悟空CRM是一种客户关系管理系统软件.它适应Windows、linux等多种操作系统,支持Apache、Nginx、IIs多种服务器软件。悟空CRM致力于为促进中小企业的发展做出更好更实用的软件,采用免费开源的方式,分享技术与经验。 悟空CRM 0.5.5 更新日志:2017-04-21 1.修复了几处安全隐患; 2.解决了任务.日程描述显示问题; 3.自定义字段添加时自动生成字段名

悟空CRM v 0.5.5 284
查看详情 悟空CRM v 0.5.5
  • {{ url_for('static', filename=user_image) }}:这是Flask中获取静态文件URL的推荐方式。url_for函数会根据您的应用配置生成正确的URL,例如/static/images/chart.png。
  • alt="动态图片":为图片提供替代文本,有助于可访问性。
  • get_flashed_messages:用于显示Flask后端发送的闪现消息(如图片不存在的提示)。

2. 使用 JavaScript 实现图片定时刷新

要实现图片的定时刷新,我们需要在前端(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 代码说明:

  • document.addEventListener('DOMContentLoaded', ...):确保DOM完全加载后再执行JavaScript。
  • imgElement = document.getElementById('dynamic-image'):获取图片元素。
  • updateImage() 函数:
    • imgElement.src.split('?')[0]:获取图片URL中不包含查询参数的部分。
    • imgElement.src = currentSrc + '?' + new Date().getTime():通过在URL末尾添加一个唯一的当前时间戳(?1678886400000 类似),欺骗浏览器认为这是一个新的URL,从而强制它重新请求图片,而不是从缓存中读取。
  • setInterval(function() { ... }, 1000):设置一个定时器,每1秒执行一次回调函数。我们用它来更新倒计时并触发图片刷新。
  • 倒计时逻辑:countdown变量用于显示距离下次刷新的秒数,当countdown归零时调用updateImage()并重置countdown。

3. 动态图片内容管理:以上传为例

为了让“图片本身变化但文件名不变”的需求有实际意义,我们需要一种机制来更新服务器上的图片文件。这里我们通过一个文件上传功能来实现。

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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号