首页 > 解决方案 > 如何从文件路径中删除 settings.MEDIA_ROOT

问题描述

我有在上传视频时为视频创建缩略图的代码 - 它看起来像这样:

views.py 发布方法:

if form.instance.thumbnail == 'images/clearpath_logo/Logo.jpg':
    thumb_title = form.instance.title.replace(" ", "")
    in_path = str(settings.MEDIA_ROOT) + "/" + str(form.instance.video_file)
    out_path = str(settings.MEDIA_ROOT) + "/images/" + thumb_title + ".png"
    if create_thumbnail(in_path, out_path):
        form.instance.thumbnail = "images/" + thumb_title + ".png"

辅助函数在哪里create_thumbnail。它看起来像这样:

def create_thumbnail(input_path, output_path):
    """
    Save first frame of video for use as video thumbnail.

    :param input_path: video input path
    :param output_path: image output path
    :return: Boolean
    """
    cap = cv2.VideoCapture(input_path)
    ret, frame = cap.read()
    if ret:
        return cv2.imwrite(output_path, frame)
    else:
        pass

我主要关心的是settings.MEDIA_ROOT从每个文件路径中删除。如何避免手动输入文件路径?或者有没有办法可以从辅助函数中创建一个表单方法并直接调用表单实例 url?我想清理这段代码。

标签: djangopython-3.x

解决方案


根据您提供的信息并牢记,我对任何表格一无所知,也不知道是什么cv2,这就是我可以整理的方法:

def create_thumbnail(video_file, title):
    """
    Save first frame of video for use as video thumbnail.

    :param video_file: video file from the form instance
    :param title: the title of the thumbnail
    :return: path to the thumbnail
    """
    in_path - f'{settings.MEDIA_ROOT}/{video_file}'
    out_path = f'{settings.MEDIA_ROOT}/images/{title}.png'

    cap = cv2.VideoCapture(input_path)
    ret, frame = cap.read()
    if ret:
        image = cv2.imwrite(output_path, frame)
        if image:
            return out_path
    return ''


if form.instance.thumbnail == 'images/clearpath_logo/Logo.jpg':
    thumb_title = form.instance.title.replace(" ", "")
    form.instance.thumbnail = create_thumbnail(form.instance.video_file, thumb_title)    

NB 请注意,您的代码不能很好地处理将视频文件命名为与其他人相同的人。缩略图将被覆盖。一种简单的解决方案是给缩略图一个随机名称。


推荐阅读