python - Django - 使用外部脚本从 url 下载图像并将它们插入到 imageField
问题描述
我正在使用嵌入视频的网站(Django 2.1),我需要使用外部脚本填充我的数据库。我有两个表,一个是父表(视频)和子表(缩略图),其中是 imageField。我需要从 url 下载缩略图并以编程方式将图像插入 ImageField。我正在与这个问题作斗争 2 天。我已经阅读了关于 stackoverflow 的一些建议,但对我没有任何帮助,我在这里放弃了。有人可以帮我吗?
这是我的模型的一部分:
#my models.py
class Video(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique = True)
video_url = models.URLField(max_length=255, unique = True)
class Thumbnail(models.Model):
name = models.CharField(max_length=50)
thumb = models.ImageField(upload_to='thumb/', null=True, blank=True)
thumb_resolution = models.CharField(max_length=50, null=True, blank=True)
videos = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='thumbnails')
这是我下载代码的简化版本,我尝试了几种不同的方法,但大多数尝试都没有错误,但 MEDIA 文件夹中没有文件。但是我的视频和缩略图之间的 OneToMany 关系已成功创建。
import requests
from io import BytesIO
from PIL import Image
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "video.settings")
import django
django.setup()
from django.core.files import File
from django.core.files.base import ContentFile
from mainSite.models import Video, Thumbnail
def download(url):
try:
r = requests.get(url)
if not r.status_code == 200:
raise Exception('file request failed with status code: ' + str(r.status_code))
return (r.content)
except Exception as ex:
print (ex)
return ('error')
VIDEO_URL = "https://videowebsite.com/video/43332"
VIDEO_THUMBS = ["https://videowebsite.com/thumb/1.jpg","https://videowebsite.com/thumb/2.jpg"]
# title, slug , video_url exist in my code
add_video = Video(title=title,slug=slug,video_url=video_url)
add_video.save()
for image in VIDEO_THUMBS:
get_file = download(image)
file_name = image.split('/')[-1]
if get_file != 'error' and len(get_file) > 0:
# I tried several different ways here but none of them work.
f = BytesIO(get_file)
Thumbnail(name=file_name, thumb=File(f), videos = add_video).save()
#No error but image does not exist on server in MEDIA folder
#--------------------------------------------
with Image.open(get_file) as img:
Thumbnail(name=file_name, thumb=ContentFile(img), videos = add_video).save()
# ValueError: embedded null byte
#--------------------------------------------
Thumbnail(name=file_name, thumb=File(get_file), videos = add_video).save()
# No error but image does not exist on server
#--------------------------------------------
with Image.open(get_file) as img:
Thumbnail(name=file_name, thumb=File(img), videos = add_video).save()
# No error but image does not exist on server
#--------------------------------------------
f = BytesIO(get_file)
with Image.open(f) as img:
Thumbnail(name=file_name, thumb=File(img), videos = add_video).save()
#Again no error but images does not exist
else:
print('error')
我真的迷路了,有人可以告诉我我在这里做错了什么吗?在大多数情况下没有错误,父表和子表之间的关系创建成功,但图像没有上传到 MEDIA/thumb 文件夹中。非常感谢您提前。
解决方案
解决方案:
from io import BytesIO
from django.core.files.base import ContentFile
from PIL import Image
for image in VIDEO_THUMBS:
get_file = download(image)
file_name = image.split('/')[-1]
# please read https://pillow.readthedocs.io/en/3.1.x/handbook/image-file-formats.html
# for available formats.
extension = 'jpeg'
f = BytesIO(get_file)
out = BytesIO()
image = Image.open(f)
image.save(out, extension)
t = Thumbnail(<all fields except thumb>)
t.thumb.save(file_name, ContentFile(out.getvalue()), save=False)
t.save()
- 将文件保存到内存 [变量
out
] - 使用 Django 的
ContentFile
类来初始化内存中的文件内容
编辑:你不需要StringIO
,BytesIO
会做这项工作。
推荐阅读
- c# - 如何在 Angular5 Ag-Grid 导出中添加自定义徽标/.jpg 文件到 Header 中的 excel
- pandas - 如何在python中通过pandas中的列名和行名获取值
- pandas - Tensorflow 2“尝试将值(63)转换为不支持的类型(
) 到张量" - html - AngularJS:引导程序中的响应高度
- ios - 在 iOS 13 模拟器上从源代码编译金属着色器会导致 PCH 错误
- python - 从列值中高效地解析和组织信息
- python - 如何让用户选择一个文件将被存储的位置?
- python - 字符串和点填充
- python-3.x - 访问网页时服务器运行出错
- javascript - Sinon 存根无法处理导出的函数