如何防止 UI 在 Python Flask 中等待线程完成?



我有一个程序可以获取音频文件并对其进行处理。

@app.route('/', methods=['GET', 'POST'])
def hello_world():
if request.method == 'GET':
return render_template('upload.html')
else:
file = request.files['file']
path = os.getcwd() + '\tempFilesAudio\'
if not os.path.exists(os.getcwd() + '\' + 'tempFilesAudio'):
os.mkdir(os.getcwd() + '\' + 'tempFilesAudio')
if not os.path.exists(os.getcwd() + '\' + 'tempFilesTransciption'):
os.mkdir(os.getcwd() + '\' + 'tempFilesTransciption')
file.save(path + secure_filename(file.filename))
file_path = path + file.filename
conv_path = convert(file_path)
print('converted:{}'.format(conv_path))
#this is a thread
Recogniser(conv_path)
print('Deleting MP3')
os.remove(file_path)
print('Deleting WAV')
os.remove(conv_path)
return render_template('upload.html')

我希望在将文件提交到线程以在后台处理后重新呈现我的 UI。但它仍然在等待。

下面是我的线程的代码:


class Recogniser:
def __init__(self, file):
self.executor = ThreadPoolExecutor(5)
self.file = file
thread = threading.Thread(target=self.run(), daemon=True, args=file)
thread.start()
def run(self):
#something

像这样创建识别器类:

class Recogniser(threading.Thread):
def __init__(self, file):
self.file = file
super().__init__()
def run(self):
#something
pass

然后,像这样启动线程:

thread_list = {}
@app.route('/', methods=['GET', 'POST'])
def hello_world():
global thread_list
# ... other logic ...
thread_id = "generate some id"
thread_list[thread_id] = Recogniser(file)
thread_list[thread_id].start()
# ... more logic ...
return render_template('upload.html')

注意:正确的方法可能涉及将线程ID缓存/保存到数据库等。但这应该适用于更简单的应用程序。

您可以使用多处理。尝试如下:

from multiprocessing import Process
class Recogniser:
def __init__(self, file):
self.file = file
thread = Process(target=self.run(), args=(file,))
thread.start()
def run(self):
#something

最新更新