python - Django - 使用外部脚本从 url 下载图像并将其插入 imageField

标签 python django django-models request

我正在开发带有嵌入视频的网站(Django 2.1),我需要使用外部脚本填充我的数据库。我有两个表,一个是父表(视频),另一个是子表(缩略图),其中是 imageField。我需要从 url 下载缩略图并以编程方式将图像插入到 ImageField 中。我和这个问题斗争了两天。我已经在 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 类使用内存中的文件内容进行初始化

编辑:您不需要StringIOBytesIO将完​​成这项工作。

关于python - Django - 使用外部脚本从 url 下载图像并将其插入 imageField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52101717/

相关文章:

python - 如何在 Django 之外使用 Django 模型?

python - TemplateDoesNotExist 错误(Python 3.6.1、Django 1.11.1、PyCharm)

python - 在 Pyrex 中包装相互依赖的结构

python - 如何在 Django 中创建/使用自定义数据库函数

python - Django 模型唯一约束异常

python - Django objects.all() 不显示任何内容

python - 核心和线程的多处理功能

python - boot2docker、docker、mac os x 上的 django

python - 无法在 VPS 上进行基本的 Django 设置

python - 带有 filter() 和 order_by() 的查询集 distinct() 不起作用