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

2024-10-04 09:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

即时通讯使用: 长颈瓶 python 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


Tags: theto文本awsapp应用程序客户机s3