首页 > 解决方案 > 如何使用 Flask 在网页上显示从服务器发送到客户端的消息

问题描述

我用 Python 创建了一个文件观察器(类似于tail-fLinux 中的),我的任务是打印日志文件的最后 10 行,当文件发生更改时,应该自动打印/显示日志。

我用 Python 编写了客户端和服务器代码服务器处理检测更改的部分,客户端显示所做的更改,为此我使用了套接字

这是server.py文件

import socket
import time
import sys
import os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1243))
s.listen(5)

def follow(thefile):
    '''generator function that yields new lines in a file
    '''
    # seek the end of the file
    thefile.seek(0, os.SEEK_END)
    
    # start infinite loop
    while True:
        # read last line of file
        line = thefile.readline()
        # sleep if file hasn't been updated
        if not line:
            time.sleep(0.1)
            continue

        yield line

logfile = open("log.log","r")
loglines = follow(logfile)

while True:
    clientsocket, address = s.accept()
    for line in loglines:
        clientsocket.send(bytes(line,"utf-8"))

这是client.py我制作成 Flask 应用程序的文件

import socket
import sys
from flask import Flask, render_template
from flask_socketio import SocketIO, send


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1243))

app=Flask(__name__)
app.config['SECRET_KEY']="mysecret"
socketio = SocketIO(app)


@app.route('/logs')
def showLogs():
    sol=[]
    while True:
        lines = s.recv(16)
        lines=lines.decode("utf-8")
        sol.append(lines)
        print(lines)

with app.app_context(), showLogs():
    render_template('index.html')


if __name__ == 'main':
    socketio.run(app)

我创建了一个log.log看起来像这样的虚拟文件

1
2
3
4
5

这是我index.html要显示输出的模板

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Logs</title>
</head>
<body>
    {% for m in sol %}
        {{m}}
    {% endfor %}
</body>
</html>

因此,当我server.py在命令行上运行文件,然后在client.py文件中进行任何更改时,log.log更改显示在我的文件的输出控制台上,client.py并且烧瓶应用程序未运行,我希望更改显示在我的网页,我是套接字编程的新手,我不知道如何显示它。

标签: pythonflasksocket.ioflask-socketio

解决方案


推荐阅读