python - 建立新连接时如何退出从 socketio.start_background_task() 创建的先前打开的函数
问题描述
每次我从客户端刷新页面时,都会与烧瓶服务器建立新连接,它会运行函数“backgroundFunction()”而不退出最近打开的函数,并且随着我一次又一次地刷新页面,数量会增加。
from flask import Flask
from flask_socketio import SocketIO, send, emit
import socket
from time import sleep
import datetime
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True
socketio = SocketIO(app , cors_allowed_origins="*" , async_mode = None , logger = False , engineio_logger = False)
def backgroundFunction():
while True:
data = "I am Data"
socketio.emit('data', data, broadcast=True)
socketio.sleep(2)
@socketio.on('connect')
def socketcon():
print('Client connected')
socketio.start_background_task(backgroundFunction)
if __name__ == ("__main__"):
socketio.run(app, port=5009)
解决方案
查看 Flask-SocketIO 存储库中的示例代码,了解一种可能的方式来实现在第一次触发事件时启动的后台作业。
代码在这里。以下是相关摘录:
thread = None
thread_lock = Lock()
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(10)
count += 1
socketio.emit('my_response',
{'data': 'Server generated event', 'count': count})
@socketio.event
def connect():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(background_thread)
推荐阅读
- react-native - 如何在 react-native-svg 元素中实现填充属性
- django - 无法部署到 Heroku - 运行“$ python manage.py collectstatic --noinput”时出错
- java - JUnit Spring MVC
- php - 无法在 VScode 上使用 Xdebug
- python - 填写数据框中缺少的日期
- android - 在某些设备上从 PlayStore 下载后,Android App Bundle 崩溃
- android - 调整多个按钮的宽度以跟随 ConstraintLayout 中换行内容宽度最大的按钮
- spring-webflux - block() 、 subscribe() 和 subscribe(-) 有什么区别
- wordpress-theming - 使用 WPBakery Page Builder 将行保存为模板不起作用
- asp.net-core - 未触发事件且 Blazor 组件不会刷新