Amit740
Amit740

Reputation: 199

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 by reading the contents of filename and sending it to my web template.

But I need to use sockets and make this process asynchronous so that auto refresh is not used. I'm using Flask as my web framework.

Upvotes: 2

Views: 4467

Answers (2)

kidz55
kidz55

Reputation: 315

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

Upvotes: 0

Matt Healy
Matt Healy

Reputation: 18531

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 = None


class ModHandler(pyinotify.ProcessEvent):
    def process_IN_CLOSE_WRITE(self, evt):
        socketio.emit('file updated')


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


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


@socketio.on('connect')
def test_connect():
    global thread
    if thread is None:
        thread = socketio.start_background_task(target=background_thread)


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

index.html

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script type="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>

Upvotes: 5

Related Questions