如何在python循环内的socketio中发出事件?

问题描述 投票:0回答:1

我有一个应用程序,它使用谷歌语音将音频文件转换为文本,然后将文本文件上传到aws s3,最后将链接和可识别的文本保存到数据库。

我需要处理一百个音频文件,所以我需要循环播放它并向客户端发出有关当前进度的事件。但是问题是,每当我向客户端发出事件时,客户端都不会收到该事件,直到所有过程都完成,并且在大多数情况下,套接字将断开连接,并在完成所有过程后重新连接。

我正在使用:Flask-socketiopython v3.8

这是应用程序的入口点:

from ats import socketio, app, db

if __name__ == '__main__':
    db.create_all()
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)

这是循环的代码段:

for file in audioFiles:

    # Convert file to text
    recognizedText = AUDIO.convert(file)

    # Upload file to aws s3
    bucket = app.config['BUCKET']
    location = app.config['UPLOAD_FOLDER']

    filePath = join(location, foldername, file)
    url = S3.upload_file(filePath, bucket)

    # Save the audiofile to database
    newAudio = {
        'productId': productId,
        'name': file,
        'link': url,
        'recognizedText': recognizedText,
    }
    Audio.add(newAudio)

    # emit event to update the client about the progress
    percent = math.floor((currentFile / float(fileCount) ) * 100)

    emit('upload_progress', {'data': percent}, room=sid, namespace='/') # This emit will not reach the client side until the loop is done.
    currentFile += 1

而且大多数情况下,在完成所有过程之前,套接字将断开连接。有什么建议或解决办法吗?当我开始学习如何使用Flask开发API时,我将非常有帮助。

python flask flask-socketio
1个回答
0
投票

经过几个小时的寻找解决方案,我只需添加一行代码就可以使它正常工作。

emit('upload_progress', {'data': percent}, room=sid, namespace='/')
eventlet.sleep() # added this line

我不完全了解其背后的逻辑,但它有效:D

© www.soinside.com 2019 - 2024. All rights reserved.