python - 如何使用 Flask 在网页上显示从服务器发送到客户端的消息
问题描述
我用 Python 创建了一个文件观察器(类似于tail-f
Linux 中的),我的任务是打印日志文件的最后 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
并且烧瓶应用程序未运行,我希望更改显示在我的网页,我是套接字编程的新手,我不知道如何显示它。
解决方案
推荐阅读
- python - 如何修复错误:具有多个元素的数组的真值不明确
- json - 托管在 Cumulocity 上的微服务
- html - 折叠时可滚动的引导侧边栏
- json - Laravel - 当 API 路由错误或找不到时如何显示 JSON?
- java - Java sort 按字母顺序排列的具有层次结构的对象列表
- bigcommerce - Bigcommerce 购物车重定向 URL 不起作用
- google-admin-sdk - HttpError 403:尝试将成员添加到组时“未授权访问此资源/api”>
- api - Hubspot API:获取所有联系人 (100+)
- firebase - 向 Firebase 上的新闻文档添加新属性
- mysql - 如何在 MySQL 查询中使用 SELECT 参数分配?