Use Flask SocketIO to update webpage everytime a local file changes

流过昼夜 提交于 2020-12-29 08:15:44

问题


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.


回答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 = 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>



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


来源:https://stackoverflow.com/questions/42549367/use-flask-socketio-to-update-webpage-everytime-a-local-file-changes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!