如何在python中返回函数后,在后台运行一些代码

时间:2018-06-19 04:20:44

标签: python multithreading

我正在尝试制作一个压缩文件组合的后台进程。我有一个python项目,它有烧瓶API。我希望当一个烧瓶API收到请求时,压缩应该开始,API返回不应该等待压缩线程结束。

我有这堆代码,但它等待完成时间

@server.route("/api/dummy/zip", methods=['GET'])
def compress_file():
    print("zipping starts at", time.time())
    file_path = ""
    file_name = ""
    comObj = compression_handler.CompressionThread()
    comObj.__int__(file_name, file_path)
    logging.info("compression starts")
    print("zipping end at", time.time())
    return "zipping has took "

和compression_handler python文件:

import zipfile
import os
from os.path import basename
import threading
import threading
from Main import logging


class CompressionThread:

def __int__(self, file_name, file_path):
    thread = threading.Thread(target=self.compress, args=(['/Users/nirmalsarswat/Desktop/jdk-8u171-macosx-x64.dmg', '/Users/nirmalsarswat/Desktop/resume-nirmal-sarswat.pdf'],))
    thread.daemon = True
    thread.start()
    logging.info('thread has started, in progress')

def compress(self, file_list):
    print("running thread in list")
    try:
        zip_path = '/Users/nirmalsarswat/Documents/newone.zip'
        print(zip_path)
        zip_file = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
        for files in file_list:
            zip_file.write(files, basename(files))
        zip_file.close()
        logging.info("compression of files is done !!!")
    except Exception as e:
        print("exception occured during compression %s" % e)

以下代码输出是这样的(在控制台调试中)

> Zipping starts at xxxxx
> running thread in list \n
> compression of files is done !!! \n
> thread has started, in progress
> compression starts
> zipping end at xxxxxx

0 个答案:

没有答案