[Python] How do I get duration of an In Memory Video in Python / Django?

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    So I was successfully using the following code to get the duration of a saved video in Django.

    def get_video_length(file_path):
    command = [
    'ffprobe',
    '-v',
    'error',
    '-show_entries',
    'format=duration',
    '-of',
    'default=noprint_wrappers=1:nokey=1',
    file_path
    ]

    try:
    output = check_output( command, stderr=STDOUT ).decode()
    except CalledProcessError as e:
    output = e.output.decode()

    return output


    But now I need to get the duration of an uploaded file before saving it. I have a serializer with a FileField and on validate method I should check the video duration. For instance:

    class VideoSerializer(serializers.Serializer):
    video = serializers.FileField(required=True, validators=[validate_media_extension, validate_video_duration])


    Then on validate_video_duration I needed to call some method like get_video_length, but I need an alternative to get the duration from the video in memory. The object that I have is an instance of InMemoryUploadedFile (https://docs.djangoproject.com/en/2.2/_modules/django/core/files/uploadedfile/)

    Continue reading...

Compartilhe esta Página