使用Python Flask AJAX动态更新图像

时间:2014-09-27 01:12:40

标签: python ajax get flask jinja2

我现在正在构建一个非常简单的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>

Channels.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响应,但即使是我试图穿上它的计时器也没有工作。原谅邋code的代码,高度易变的代码经常被改变-_-

1 个答案:

答案 0 :(得分:1)

我不知道有一个特殊的&#34;使用一些Flask扩展来处理Ajax的方法,但在&#34; normal&#34; Ajax流首先你需要使用url_for在Ajax调用中放入正确的url并返回以某种方式格式化的数据(在我的JSON示例中),而不是再次呈现模板:

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

所以,在控制器的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'} 

看看我使用$(&#39;#sst&#39;)所以你必须输入你的HTML:

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