Download a remote image and save it to a Django model

后端 未结 6 914
醉话见心
醉话见心 2020-12-01 01:52

I am writing a Django app which will fetch all images of particular URL and save them in the database.

But I am not getting on how to use ImageField in Django.

6条回答
  •  隐瞒了意图╮
    2020-12-01 02:40

    Similar to @boltsfrombluesky's answer above you can do this in Python 3 without any external dependencies like so:

    from os.path import basename
    import urllib.request
    from urllib.parse import urlparse
    import tempfile
    
    from django.core.files.base import File
    
    def handle_upload_url_file(url, obj):
        img_temp = tempfile.NamedTemporaryFile(delete=True)
        req = urllib.request.Request(
            url, data=None,
            headers={
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
            }
        )
        with urllib.request.urlopen(req) as response:
            img_temp.write(response.read())
        img_temp.flush()
        filename = basename(urlparse(url).path)
        result = obj.image.save(filename, File(img_temp))
        img_temp.close()
        return result
    

提交回复
热议问题