flask_socketio 实时显示 log

Posted on Posted in python

实时显示 log

目录结构

realTimeLog/
├── index.py
├── Pipfile
├── Pipfile.lock
└── templates
    └── index.html

index.py

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import time
import subprocess
from threading import Lock, Thread
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit

async_mode = None

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)


thread = None
thread_lock = Lock()

def background_thread():
    """Example of how to send server generated events to clients."""
    global popen
    popen=subprocess.Popen(['tail','-f',"/root/tmp.log"],bufsize=10000,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
    global pid
    pid=popen.pid
    print('Popen.pid:'+str(pid))
    count = 0
    nullStr=''
    while True:
        socketio.sleep(0.05)
        count += 1
        line=popen.stdout.readline().strip().decode('utf-8')
        nullStr += line+'\n'
        if nullStr and count % 10==0:
            socketio.emit('server_response',{'data': nullStr, 'count': count},
                      namespace='/nf') 
            print(nullStr)
            nullStr = ''

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

@socketio.on('connect', namespace='/nf')
def nf_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)

if __name__ == '__main__':
    socketio.run(app, debug=True, host='0.0.0.0', port=80)

templates/index.html

<!DOCTYPE HTML>
<html>
<head>
<title>Index Page</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<style type="text/css">
#showContent{
    width:100%;
    height:500px;
    overflow:auto;
    word-break:break-all;
}
</style>
</head>

<body>
Index Content
<br /><textarea id="showContent"></textarea>
</body>
</html>
<script type="text/javascript" charset="utf-8">
        socket = io.connect('http://192.168.213.130:80/nf');
        socket.on('server_response',function(msg){
        console.log(msg)
        element = document.getElementById("showContent");
        if(element){
            if(element.value.length > 100000){
                element.value="";
            }
            element.value += (msg.data);
            console.log(element.value.length)
            element.scrollTop = element.scrollHeight;
        }
        });
</script>

Pidfile

[[source]]
name = "pypi"
url = "https://mirrors.aliyun.com/pypi/simple/"
verify_ssl = true

[dev-packages]

[packages]
python-dotenv = "*"
gevent = "*"
eventlet = "*"
flask-socketio = "*"

[requires]
python_version = "3.5"
» 转载请注明来源:若我若鱼 » flask_socketio 实时显示 log

Leave a Reply

Your email address will not be published. Required fields are marked *

19 − 2 =