我需要在使用flask-socketio
的网页上显示已连接客户端的数量,并且编写此代码来检查connected
和disconnected
的连接。
app = Flask(__name__)
socketio = SocketIO(app)
clients = []
@socketio.on('connect', namespace='/')
def connect():
clients.append(request.namespace)
@socketio.on('disconnect', namespace='/')
def disconnect():
clients.remove(request.namespace)
然后我渲染这样的模板
return render_template_string(TABLE_TEMPLATE, data=data, clients=len(clients))
在html部分中,我这样称呼
<h1>{{ clients }} </h1>
但是在网页上,即使客户端已连接,它也会持续显示0
,我从客户端获得输出并且连接了它,它应该显示1
2
取决于连接的客户端数。即使我打印此
print(len(clients))
返回0
。
这是我的完整应用代码。
from flask import Flask, request, render_template_string
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
clients = []
@socketio.on('connect', namespace='/')
def connect():
clients.append(request.namespace)
@socketio.on('disconnect', namespace='/')
def disconnect():
clients.remove(request.namespace)
TABLE_TEMPLATE = """
<h1>{{ clients }} </h1>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<table style="width: 100%">
<thead>
<th>Client</th>
<th>IP</th>
<th>Status</th>
</thead>
<tbody>
{% for row in data %}
<tr>
<td><center>{{ row.client }}</td></center>
<td><center>{{ row.ip }}</td></center>
<td><center>{{ row.status }}</td></center>
</tr>
{% endfor %}
</tbody>
</table>
"""
@app.route("/device_add", methods=['POST'])
def device_add():
name = request.args.get('name')
with open('logs.log', 'a') as f:
f.write(f'{name} Connected USB from IP: {request.remote_addr} \n')
return 'ok'
@app.route("/device_remove", methods=['POST'])
def device_remove():
name = request.args.get('name')
with open('logs.log', 'a') as f:
f.write(f'{name} Disconnected USB from IP: {request.remote_addr}\n')
return 'ok'
@app.route("/", methods=['GET'])
def device_list():
keys = ['client', 'ip', 'status']
data = []
with open('logs.log', 'r') as f:
for line in f:
row = line.split()
data.append(dict(zip(keys, [row[0], row[-1], row[1]])))
return render_template_string(TABLE_TEMPLATE, data=data, clients=len(clients))
if __name__ == "__main__":
app.run(threaded=True)