Skip to main content
 首页 » 编程设计

python之使用 Python Flask AJAX 动态更新图像

2025年05月04日27arxive

我现在正在构建 1 个非常简单的 Web 应用程序,但对 Flask 和 Jinja(实际上是整个 Web 开发)还很陌生。

我有一个监视文件夹,它将永远通过 ftp 脉冲将图像发送给它。此 wtch 文件夹将永远只有一张图像。每隔 1 分钟,旧图像就会被新图像替换,并带有新的时间戳。

我也想动态更新页面(和显示的时间戳),而不必重新加载我稍后添加的任何横幅或静态图像。我只想更新“Channels.Jinja”示例中的以下两行。

    <br>{{screenshot_datetime}}<br/> 
    <img src={{screenshot_location}} width="100%"/> 

Channels.Jinja

<!DOCTYPE HTML> 
<html> 
<head> 
<title>Training</title> 
</head> 
 
<body bgcolor=white> 
 <div id=main> 
 <br>Date and Time of Screenshot <br/> 
 <br>{{screenshot_datetime}}<br/> 
 <img src={{screenshot_location}} width="100%"/> 
 </div> 
 
 <div id='test'> 
<p> 
<script> 
var myVar=setInterval(function(){get_image()},1000); 
 
function get_image() { 
    $.ajax({ 
    type: 'GET', 
    cache: false, 
    url: 'get_data', 
    success: function({{data}}) { 
    $('img').attr('src', data);   
    } 
    }); 
} 
</script> 
</p> 
</div> 
</body> 
</html> 

channel .py

 def render_channel_route(cr): 
 static_folder = os.path.join('static',cr) 
file_list = os.listdir(static_folder) 
 
channel_files = [f for f in file_list if f.startswith(cr)] 
 
if not channel_files : 
    logger.error('Could not find image file for Channel. File should start with {0}'.format(cr)) 
    abort(404) 
img = os.path.join(static_folder,file_list[0]) 
 
ts = get_time_from_filename(file_list[0],cr) 
 
return render_template('Channels.jinja',screenshot_datetime=time.strftime('%c',ts),screenshot_location=img) 
 
 
 
@app.route('/channel01-10') 
def first_tab(): 
return render_channel_route('channel01-10') 
 
 
@app.route('/get_data', methods=['GET']) 
def get_data(): 
   return render_template('Channels.jinja', 
 screenshot_datetime=time.strftime('%c',ts),screenshot_location=img) 

我很茫然,我一直在摸索着。欢迎任何建议!我在刷新时看到 304 响应,但即使是我尝试设置的计时器也无法正常工作。请原谅草率的代码,高度易变的代码经常更改 -_-

请您参考如下方法:

我不知道有一种“特殊”的方法可以使用一些 Flask 扩展来处理 Ajax,但是在“正常”的 Ajax 流程中,您首先需要使用 url_for 将正确的 url 放入您的 Ajax 调用中并返回数据以某种方式格式化(在我的 JSON 示例中)并且不再呈现模板:

$.ajax({ 
    type: 'GET', 
    cache: false, 
    url: "{{ url_for('get_data') }}",  
    success: function(resp){ 
        $('img').attr('src', resp.url); 
        $('#sst').html(resp.time); 
    } 
}); 

因此,在 Controller 的 get_data 函数中,您必须再次获取图像的时间和路径,然后返回一些类似的内容(以适应我之前的示例):

from flask import json 
@app.route('/get_data', methods=['GET']) 
def get_data(): 
    #get time and path 
    time=...  
    path=...  
    return json.dumps({time:time,url:path}), 200, {'Content-Type':'application/json'}  

看,我使用 $('#sst') 所以你必须输入你的 HTML:

<br><span id='sst'>{{screenshot_datetime}}</span><br/>