Skip to content Skip to sidebar Skip to footer

Use Flask Socketio To Update Webpage Everytime A Local File Changes

I need to update my webpage every time my local file:filename is changed. Without the use of sockets, I can simply refresh the page every 1 second and get it done. I was doing this

Solution 1:

Below is an example Flask application which watches a file and emits a socket message whenever the file is changed. Note that this assumes you are on the Linux platform (for file watching)

app.py

from flask import Flask, render_template
from flask_socketio import SocketIO
import pyinotify

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = NoneclassModHandler(pyinotify.ProcessEvent):
    defprocess_IN_CLOSE_WRITE(self, evt):
        socketio.emit('file updated')


defbackground_thread():
    handler = ModHandler()
    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, handler)
    wm.add_watch('test.log', pyinotify.IN_CLOSE_WRITE)
    notifier.loop()


@app.route('/')defindex():
    return render_template('index.html', async_mode=socketio.async_mode)


@socketio.on('connect')deftest_connect():
    global thread
    if thread isNone:
        thread = socketio.start_background_task(target=background_thread)


if __name__ == '__main__':
    socketio.run(app, debug=True)

index.html

<scripttype="text/javascript"src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script><scripttype="text/javascript"charset="utf-8">var socket = io.connect('http://' + document.domain + ':' + location.port);
    socket.on('connect', function() {
        socket.emit('my event', {data: 'I\'m connected!'});
    });
    socket.on('file updated', function(data) {                                  
        console.log('the file has been updated');
    });

</script>

Solution 2:

You can specify the content of your page in the socket like this :

socketio.emit('connect',
                     {'field_doc': "some content", 'another_field' :"some other content"})

Post a Comment for "Use Flask Socketio To Update Webpage Everytime A Local File Changes"