djangodjango-storageamazon-elastic-transcoder

Django - Encode video and audio files only when the file is changed


I'm using django-storages for storing media files on Amazon S3. I've developed an interface using boto3 to use Elastic Transcoder for encoding videos or audio files. Also for video files I'll add a watermark logo still using Elastic Transcoder.

The flow is the following:

  1. The client app upload the file thought the REST API I developed -- DONE
  2. Django stores the file on Amazon S3 -- DONE
  3. If it's a video or audio, Django will launch a Amazon Elastic Transcoder Job to encode the file. The output file will be added to a different path on the same S3 bucket.
  4. Using Amazon SNS, Django will be notified when the encoded file will be ready

To launch the encoding process, I was thinking to use the post_save. So I could check if the file has been uploaded, then launch Amazon Elastic Transcoder. Example:

@receiver(post_save, sender=MyModel)
def encode_file(sender, instance, created, **kwargs):
    if instance.content_type in ['video'] and instance.file:
        encode_file(instance.file) # Launch Amazon Elastic Transcoder

Is there a better way to launch the encoding process only for video or audio files and only when the file is changed?


Solution

  • You can check file update in models.py:

    class MyModel(models.Model):
        ...
    
        def save(self, *args, **kwargs):
            if not self.id:
                pass # for create
            else:
                # update
                this = MyModel.objects.get(id=self.id)
                if this.file != self.file:
                    encode_file(instance.file) # Launch Amazon Elastic Transcoder
            return super(MyModel, self).save(*args, **kwargs)
    

    before super().save() file is different in database and memory,so you can check update