gpt4 book ai didi

python - Celery 处理任务并修改模型字段

转载 作者:太空宇宙 更新时间:2023-11-03 17:34:25 24 4
gpt4 key购买 nike

我想使用 ffmpegcelery 将视频转换为 mp4 来执行异步任务。当用户上传视频时,它将是original_video并保存。之后,我希望 celery 将其转换为 mp4_720 字段的不同版本。然而,我对如何使用 celery 应用该逻辑感到困惑。

app.models.py:

class Video(models.Model):
title = models.CharField(max_length=75)
pubdate = models.DateTimeField(default=timezone.now)
original_video = models.FileField(upload_to=get_upload_file_name)
mp4_720 = models.FileField(upload_to=get_upload_file_name, blank=True, null=True)
converted = models.BooleanField(default=False)

app.views.py:

def upload_video(request):
if request.POST:
form = VideoForm(request.POST, request.FILES)
if form.is_valid():
video = form.save(commit=False)
video.save()

// Celery to convert the video
convert_video.delay(video)

return HttpResponseRedirect('/')
else:
form = VideoForm()
return render(request, 'upload_video.html', {
'form':form
})

app.tasks.py:

@app.task
def convert_video(video):

// Convert the original video into required format and save it in the mp4_720 field using the following command:
//subprocess.call('ffmpeg -i (path of the original_video) (video for mp4_720)')

// Change the converted boolean field to True

// Save

基本上我的问题是如何将转换后的视频保存在 mp4_720 中。我们将非常感谢您的帮助和指导。谢谢。

** 更新 **

我希望该方法执行的操作是首先转换 video.original_video,然后将转换后的视频保存在 video.mp4_720 字段中。如果一切都正确完成,请将 video.converted 更改为 True。如何定义执行此操作的方法?

最佳答案

首先,您可能不想将 video 对象传递给 celery - 请参阅 this询问详细信息。

所以你想这样调用它:

        convert_video.delay(video.id)

然后

logger = logging.getLogger(__name__)  # assuming you have set up logging elsewhere

@app.task
def convert_video(video_id):
video = Video.objects.get(video_id)

cmd = ['ffmpeg', '-i', video.original_video.path, video.mp4_720.path]
log.info('running %s', ' '.join(cmd))
proc = subprocess.Popen(cmd)
proc.subprocess.wait()

if p.returncode != 0:
log.error('command failed with ret val %s', p.returncode)
log.info(p.stderr)
log.info(p.stdout)
else:
video.converted = True
video.save()
log.info('video converted ok')

关于python - Celery 处理任务并修改模型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31413129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com