我想使用ffmpeg
和celery
将视频转换为mp4进行异步任务。当用户上传视频时,该视频将用于original_video
并保存。之后,我希望芹菜将其转换为mp4_720
字段的不同版本。然而,我对如何使用芹菜应用该逻辑感到困惑。
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。非常感谢您的帮助和指导。谢谢你。
** update **
我想让这个方法做的是首先转换视频。然后将转换后的视频保存在video.mp4_720字段中。如果所有操作都正确,请更改视频。转换为True。我如何定义方法来实现这个功能?
首先,您可能不希望将video
对象传递给芹菜—详细信息请参见这个问题。
你可以这样命名它:
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')