flask socketio 轮询 日志

app.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/4/30 0030 13:38
# @File    : app.py
# @author  : dfkai
# @Software: PyCharm
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock
from flask import Flask, render_template

app = Flask(__name__)  # static_folder="static",template_folder="templates",static_url_path="/static")
app.config['SECRET_KEY'] = 'secret!'
async_mode = None
socketio = SocketIO(app)
thread = None
thread_lock = Lock()


@app.route('/')
def index():
    return render_template('index.html')


# 连接时
@socketio.on('connect', namespace='/conn_logging')
def connect():
    global thread
    print("connect")
    socketio.emit('message',
                  {'data': "hello,world!"}, namespace='/conn_logging', callback=ack)
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)


# 关闭时
@socketio.on('disconnect_request', namespace='/conn_logging')
def disconnect_request():
    print('Client disconnected')
    disconnect()


@socketio.on("fuck", namespace="/conn_logging")
def fuck(fuck):
    print('received message: ' + str(fuck))


def ack():
    # 似乎无用
    print('message was received!')


def background_thread():
    file = r"flask.log"
    with open(file, "r") as f:
        while True:
            socketio.sleep(1)
            for line in f.readlines():
                socketio.emit('message',{'data': line}, namespace='/conn_logging', callback=ack)


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

index.html




    
    
    
    


日志管理

你可能感兴趣的:(flask socketio 轮询 日志)