每当本地文件更改时,使用Flask SocketIO更新网页 [英] Use Flask SocketIO to update webpage everytime a local file changes

查看:43
本文介绍了每当本地文件更改时,使用Flask SocketIO更新网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次更改本地文件:文件名时,我都需要更新我的网页.在不使用套接字的情况下,我只需每1秒钟刷新一次页面并将其完成即可.我通过读取文件名的内容并将其发送到我的Web模板来做到这一点.

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.

但是我需要使用套接字并使该过程异步,以便不使用自动刷新.我正在使用Flask作为我的Web框架.

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.

推荐答案

下面是一个示例Flask应用程序,该应用程序监视文件并在更改文件时发出套接字消息.请注意,这假设您在Linux平台上(用于观看文件)

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>

这篇关于每当本地文件更改时,使用Flask SocketIO更新网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆