python使用函数而无需等待它的返回(即发即忘)?

时间:2019-09-24 13:06:41

标签: python-3.x process python-asyncio fire-and-forget

我想下载文件并使用files功能将其保存在dwd文件夹中,但我不想等到文件下载完毕后才想在后台运行下载功能并做出响应用文件功能查看我试图使用multiprocessing.Process不能按预期工作。

 def files(request):
     # Get papram needed
     g_id = request.GET.get('g_id')
     d_id = request.GET.get('d_id')
     o_id = request.GET.get('o_id')
     m_id  = request.GET.get('m_id')


    download_url = (f"http://example.com/embed?video={m_id}&d=1")
    r = requests.head(download_url)
    content_length = r.headers['Content-length']
    video_path_name = (f'streamapp/static/files/{did}_{m_id}.mp4')

    if os.path.exists(video_path_name):
        currnt_lenght = os.path.getsize(video_path_name)
        progress = (int(currnt_lenght) *100)/ int(content_length)
        progress = round(progress, 2)
    else:
        run_download = Process(target=dwd_file(filepath=video_path_name, download_url=download_url))
        run_download.daemon = True
        run_download.start()
        progress = '0'

    context = {'g_id': g_id, 'd_id': d_id,
               'o_id': o_id, 'm_id': m_id,
               'video_path_name': video_path_name,
               'download_url': download_url,
               'progress': progress}
    return render(request, 'pages/upload.html', context)


def dwd_file(filepath, download_url):
    if not os.path.exists(filepath):
        r = requests.get(download_url, stream=True)
        with open(filepath, 'wb') as f:
            for chunk in r.iter_content():
                f.write(chunk)

0 个答案:

没有答案