Django - 使用外部脚本从URL下载图像并将它们插入imageField



我正在网站上使用嵌入式视频(Django 2.1(,我需要使用外部脚本填充我的数据库。我有两个表,一个是父表(视频(和子表(缩略图(,其中是图像字段。我需要从 url 下载缩略图并以编程方式将图像插入图像字段。我正在与这个问题作斗争 2 天。我已经在这里阅读了几个关于堆栈溢出的建议,但对我没有任何用处,我在这里放弃了。有人可以帮我吗?

这是我模型的一部分:

#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 文件夹中没有文件。但是我的视频和缩略图之间的一对多关系已成功创建。

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类使用内存中的文件内容进行初始化

编辑:你不需要StringIOBytesIO会做这项工作。

到目前为止,我能够克服它,但我必须将图像保存到磁盘,然后再次读取文件,这可以根据需要工作。

for image in VIDEO_THUMBS:
get_file = download(image)
file_name = image.split('/')[-1]
if get_file != 'error' and len(get_file) > 0:  
with open('temp/temp.jpg', 'wb') as f:
f.write(get_file)                
with open('temp/temp.jpg', 'rb') as f:
fi = f.read()
t = Thumbnail(name=file_name, videos = add_video)
t.thumb.save(file_name, ContentFile(fi), save=False)
t.save()
else:
print('error')

最新更新