拜托,我已经搜索了 2 天了。我必须在另一个文件上运行一些长函数,所以我使用 Redis Queue 在后台运行这些函数(工作正常)。但是我想在后台任务完成后在客户端进行确认,所以我使用 Flask SocketIO 来发送消息。
这是示例代码。假设 test.py
是主文件。我想在后台执行 task()
(来自 utils.py
),完成后,在 task()
完成后向客户端发送消息。
test.py
from flask import Flask, render_template, request, redirect, url_for
from flask_socketio import SocketIO, send, emit
from worker import conn
from redis import Redis
from rq import Queue
import time
from utils import task
app = Flask(__name__)
q = Queue(connection=Redis())
@ app.route("/update")
def update():
job = q.enqueue(task) # Running 'task' function in background
return render_template("index_copy.html")
if __name__ == '__main__':
app.run(debug=True)
utils.py
from flask import Flask, render_template, request, redirect, url_for
from flask_socketio import SocketIO, send, emit
import time
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@socketio.on("message")
def task(msg):
time.sleep(3)
send(msg) # (Socketio) Sending message to client once the background task is done
index_copy.html
<script type="text/javascript" charset="utf-8">
const socket = io();
socket.emit("message", "hello");
socket.on('message', function (msg) {
$("#mensaje").append("<p>" + msg + "</p>");
});
</script>