我正在网站(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文件夹中。预先非常感谢。
答案 0 :(得分:1)
解决方案:
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
] ContentFile
类初始化内存中的文件内容 编辑:您不需要StringIO
,BytesIO
将完成这项工作。
答案 1 :(得分:0)
到目前为止,我已经能够克服它,但是我必须将映像保存到磁盘,然后再次读取文件,这可以根据需要工作。
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')