【问题标题】:how to keep UI from waiting for a thread to complete in python flask?如何防止 UI 在 python 烧瓶中等待线程完成?
【发布时间】:2020-06-28 19:56:46
【问题描述】:

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

@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

【问题讨论】:

    标签: python python-multithreading background-thread


    【解决方案1】:

    您可以使用多处理。试试这样:

    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
    

    【讨论】:

    • 网页仍在等待进程完成
    • 不确定。问题可能是你如何称呼课程。尝试将此过程用作方法而不是单独的类。
    • 问题是我的请求处理时间太长,我想知道如何将它从主线程中分离出来。
    • 所以您在 run(self) 或 hello_world() 中的请求有问题?如果在 hello_world 中,只需在单独的进程中像 run(self) 一样使用它,并在 UI 线程中检查是否处于活动状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    相关资源
    最近更新 更多