【问题标题】:Download Images from CSV column to Django ImageField将图像从 CSV 列下载到 Django ImageField
【发布时间】:2017-05-15 12:57:57
【问题描述】:

由于我在 django 中使用 ImageField 模型,我需要将这些图像以及相应的标题和描述保存到数据库中。

response.content 返回图像的二进制 blob,ImageField 需要一个有效的图像,我只是在这里遇到了障碍。

这是我的示例 csv 数据

title   description     image
Item 1  Description 1   http://www.imgur.com/784/77987987.jpg
Item 2  Description 2   http://www.image.com/images/797-oijio.jpg
Item 3  Description 3   https://www.google.com/logo.jpg

这是我的图像模型,

class Image(BaseModel):
    title = models.CharField(max_length=200, unique=True)
    description = models.CharField(max_length=400, null=True, blank=True)
    image = models.ImageField(null=True, blank=True)

    class Meta:
        db_table = 'images'
    def __str__(self):
        return self.title




import csv
import validators
from django.core.management.base import BaseCommand
import requests
from images.models import Image

def get_image_content(url):
    resp = requests.get(url)
    if resp.status_code == 200:
        return resp.content

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('filepath'),

    def handle(self, **options):
        csv_path = options["filepath"]
        with open(csv_path) as f:
            data = list(csv.DictReader(f))

        images = []
        for row in data:
            if validators.url(row['image']):
                img, _ = Image.objects.get_or_create(title=row['title'])
                img.description = row['description']
                # download image, populate filename and img_raw_data variables
                img.image.save(filename, img_raw_data, save=True)
                img.save()

【问题讨论】:

    标签: python django csv django-models django-rest-framework


    【解决方案1】:

    你可以的

    import urllib
    from urlparse import urlparse
    from django.core.files import File
    
    #code
    result = urllib.urlretrieve(row['image'])
    filename = urlparse(row['image']).path.split('/')[-1]
    
    img.image.save(
            filename,
            File(open(result[0]))
            )
    img.save()
    

    【讨论】:

    • 谢谢,它按预期工作。无论如何,我们可以以一种更优化的方式来做吗?
    • 这是推荐的用法之一。如果你正在考虑速度,你需要像threads这样的并行编程
    • 我还有一个问题,urllib.urlretrieve(row['image']) 是否类似于通过请求提供的类似功能?
    • 我已经这样做了 def get_image_content(url): resp = requests.get(url) if resp.status_code == 200: return resp.content 但它返回给我一个二进制 blob 对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2011-12-15
    • 2012-04-29
    相关资源
    最近更新 更多