如何在 flask-socketio 中逐个显示消息而不是批量显示消息?

How to display messages one by one in flask-socketio and not in bulk?

提问人:Maydae 提问时间:11/6/2023 更新时间:11/6/2023 访问量:21

问:

我正在学习和构建一个总结模型。但总结需要很长时间。我想向用户显示后台发生的事情的消息。我使用 Flask 作为后端,使用 Flask-SocketIO 来维护通信。 我希望它能一一显示消息,但当所有过程都完成时,它会批量显示它。有没有办法实时显示消息?

这是我正在测试的一些后端代码:

from flask import Flask, render_template, request, redirect, url_for
from flask_socketio import SocketIO, emit
from werkzeug.utils import secure_filename
import os

summarizer = pipeline("summarization", model="facebook/bart-base")


app = Flask(__name__)

socketio = SocketIO(app)


UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

ALLOWED_EXTENSIONS = {'txt', 'pdf'}

global pdf_path


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def find_summary():
    # Preprocess the text
    global pdf_path
    processed_text = preprocess(pdf_path)
    emit('summary', {'text': processed_text})


@app.route('/')
def home():
    return render_template("home.html")


@app.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        # Check if the post request has any file parts
        if not request.files:
            return redirect(request.url)

        file = request.files['file']

        # If the user does not select a file, the browser should also submit an empty part without a filename
        if file.filename == '':
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(file_path)
            global pdf_path
            pdf_path = file_path
            return redirect(url_for('summarize'))

    return render_template("create.html")


@app.route('/summarize')
def summarize():
    return render_template('summarize_page.html')


@socketio.on('connect')
def handle_connect():
    emit('status', {'text': 'File Uploaded Successfully'})
    emit('status', {'text': 'Summarization Begin.'})
    find_summary()


if __name__ == "__main__":
    socketio.run(app, debug=True, allow_unsafe_werkzeug=True)

这是它应该显示消息的 html 页面:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

  <div id="statusMessage"></div>
  <div id="summaryResult"></div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
    var socket = io.connect();
    socket.on('connect', function() {
        console.log('connected');
    });

    socket.on('status', function(text) {
        console.log('received');
        var text = text['text'];
        document.getElementById("statusMessage").innerHTML += text + "<br>";
    });

    socket.on('summary', function(text) {
        console.log("Summary complete");
        var summary = text['text'];
        document.getElementById("summaryResult").innerHTML += "<br><br>"+ summary + "<br>";
    });
</script>
</html>

我确实尝试使用 等待它显示消息,不幸的是它没有。 我还试图将发出的消息划分为不同的函数,以为它首先执行整个函数并进一步移动,但在那里非常错误。time.sleep()

python flask 后端 实时 flask-socketio

评论

0赞 Swifty 11/6/2023
我知道在执行过程中显示动态信息的唯一方法是在您的 html 页面中使用一些 ajax:您可以使用 api.jquery.com/load

答: 暂无答案