【问题标题】:Celery to process task and modify the model fieldsCelery 处理任务和修改模型字段
【发布时间】:2015-10-03 11:22:46
【问题描述】:

我想使用 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。我如何定义这样做的方法?

【问题讨论】:

  • 您在问正确的ffmpeg 命令行参数是什么?
  • @scytale 我知道执行 ffmpeg 的命令。我不知道如何获取原始视频 -> 转换它 -> 并将其保存在 mp4_720 中。请你帮帮我。
  • 您能否准确解释您发布的代码中缺少或损坏的内容?
  • @scytale 我对 convert_video() 方法感到困惑。我希望该方法首先转换video.original_video,然后将转换后的视频保存在video.mp4_720 字段中。如果一切都已正确完成,请将 video.converted 更改为 True。我如何定义这样做的方法?
  • 请用您刚刚在评论中提供的说明更新您的问题

标签: python django ffmpeg celery


【解决方案1】:

首先,您可能不想将 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')

【讨论】:

  • 非常感谢。我会检查并很快回来。
  • Scytale,对不起,我真的很忙。您认为我如何将文件名赋予 mp4_720,因为它需要此函数的文件名get_upload_file_name()
  • 否 - 该函数负责创建文件名 - 请参阅 [docs.djangoproject.com/en/1.8/ref/models/fields/…
猜你喜欢
  • 2018-06-03
  • 2013-10-16
  • 2012-10-29
  • 2018-05-24
  • 2012-06-06
  • 2012-08-26
  • 2019-02-16
  • 2016-05-03
  • 2018-06-10
相关资源
最近更新 更多