django - 如何从文件路径中删除 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?我想清理这段代码。
解决方案
根据您提供的信息并牢记,我对任何表格一无所知,也不知道是什么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 请注意,您的代码不能很好地处理将视频文件命名为与其他人相同的人。缩略图将被覆盖。一种简单的解决方案是给缩略图一个随机名称。
推荐阅读
- bash - 在添加两个表的行时合并列
- python - 函数可以在 for 循环语句中返回两次吗
- html - 包含嵌套的内联元素
- android - 2D 图像在垂直平面上水平渲染。为什么?
- java - 自动回复广播接收者收到的消息
- javascript - 只有一些 CSS 自定义属性有效,尽管所有属性都清楚地显示在 HTML 中并由检查器显示
- .net - 为什么我通过拉动 dotnet docker 映像得到 sha256 验证错误?
- windows - Makefile CMD 长路径限制
- office365 - 有人在 Office365 桌面应用程序上部署了 Outlook 加载项吗?
- c++ - 初始化 C++ 基类而不键入整个基类类型两次