【问题标题】:Django Async Views, AsyncIODjango 异步视图,AsyncIO
【发布时间】:2020-12-07 11:31:20
【问题描述】:

是否可以在 django 主视图函数中调用异步函数,并在第二个函数继续执行之前返回 main?由于视频转换花费的时间太长,我需要在转换完成之前返回媒体路径。

views.py

async def optimize(request):
    
    serializer_data = FileUploadSerializer(data=request.FILES).custom_validation()
    media_paths = {}
    
    for data in serializer_data.validated_data:
        #converting video
        if data == 'video':
            media_paths['video'] = []            
            for file in serializer_data.validated_data['video']:
 
                file_path = file.file.name
                file_name = generate_file_name()
                new_path = os.path.join(settings.BASE_DIR, 'media')
                extension = file.name.rsplit('.', 1)[-1]
                
                loop = asyncio.get_event_loop()
                loop.create_task(video_converter.start_convert(file_path, file_name, new_path))
                # loop.run_until_complete(video_converter.start_convert(file_path, file_name, new_path))
                
                media_paths['video'].append(request.build_absolute_uri() + "media/video/" + file_name + "." + extension)
        

    
    return JsonResponse(media_paths)

video_converter.py

    clip = VideoFileClip(f"{file_path}")
    if round(clip.w/clip.h, 2) == 1.78:
        if clip.h < 720:     
            clip.write_videofile(f"{new_path}\\video\{file_name}.mp4", fps=24)
            clip.close()
        else:
            clip_resized = clip.resize(height=720)
            clip_resized.write_videofile(f"{new_path}\\video\{file_name}.mp4", fps=24)
            clip.close()
        return new_path + file_name + '.mp4'
    else:
        clip.close()
        raise Exception("Uploaded video resolution is not supported")

【问题讨论】:

    标签: python django django-rest-framework python-asyncio


    【解决方案1】:

    找到了我上面描述的问题的解决方案。 我使用了python线程模块并将变量传递给新创建的胎面,就像这样。 当 main 函数执行完毕并返回时,线程将使用 main 函数传递给它的参数开始执行。

    import threading
    
    def my_func(a):
        time.sleep(5)
        print(f"my number is {a}") 
    
    def main(a, b):
        task = threading.Thread(target=my_func, args=(a,))
        task.daemon = True
        task.start()
        return a + b
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多