2

I have 1 very simple web application I am building right now but am very new to flask and jinja (and web development as a whole actually).

I have a watch folder, which will be getting an image sent to it via ftp on a pulse for ever. This wtch folder will only ever have one image in. Every 1 minute, the old image is replaced by a new image, with a new timestamp.

I would like to dynamically update the page, (and displayed timestamp) on a pulse as well, without having to reload any banners or static images that I will add later. I only want to update the following two lines out of the "Channels.Jinja" sample to follow.

    <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)

Im at a loss, Ive been bumbling around for a while now. Any and all advice is welcome! I am seeing a 304 response upon refresh, but not even the timer i am trying to put on it is working. Pardon sloppy code, highly volatile code is getting changed often -_-

1 Answer 1

1

I don't know it there is a "special" way to deal with Ajax using some Flask extension, but in the "normal" Ajax flow first you need to use url_for to put the correct url in your Ajax call and return the data formatted in some way (in my example in JSON) and not to render the template again:

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

So, in your get_data function in your controller you have to get the time and the path again for your image an then return some like this (to fit in my example before):

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'} 

Look that I use $('#sst') so you have to put in your HTML:

<br><span id='sst'>{{screenshot_datetime}}</span><br/>
Sign up to request clarification or add additional context in comments.

2 Comments

Im still struggling to get it to work right now. I am going to have 8 or so channels so each /get_data call will need a referene to the channel, aka the "cr" variable. in render_channel_route. I am not sure how to serve the img location (which should be osmething like \static\channel01-10\channel01-10_timestamp.png since I will need to parse the filename to get the timestamp and filename (since this is watch folder I dont control naming). I tried adding the code you suggested but I havent progressed. need pulse requestI will need to investigate furhter tomorrow, so thank you for the input!
To send the channels' number (for example) to the get_data function you can pass it as a query string. If you know the channel number when jinja2 renders you can use {{ url_for('get_data', channel=03) }} and if you get the channel number in a more dynamic way you can use '{{ url_for('get_data') }}' + '?channel=' + your_channel_var_set_somewere. And of course, in your controller to get the query you have to use the Flask request object: ct_number = request.args.get('channel', None).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.