Download a remote image and save it to a Django model

后端 未结 6 922
醉话见心
醉话见心 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:50

    Django Documentation is always good place to start

    class ModelWithImage(models.Model):
        image = models.ImageField(
            upload_to='images',
        )
    

    UPDATED

    So this script works.

    • Loop over images to download
    • Download image
    • Save to temp file
    • Apply to model
    • Save model

    .

    import requests
    import tempfile
    
    from django.core import files
    
    # List of images to download
    image_urls = [
        'http://i.thegrindstone.com/wp-content/uploads/2013/01/how-to-get-awesome-back.jpg',
    ]
    
    for image_url in image_urls:
        # Stream the image from the url
        response = requests.get(image_url, stream=True)
    
        # Was the request OK?
        if response.status_code != requests.codes.ok:
            # Nope, error handling, skip file etc etc etc
            continue
        
        # Get the filename from the url, used for saving later
        file_name = image_url.split('/')[-1]
        
        # Create a temporary file
        lf = tempfile.NamedTemporaryFile()
    
        # Read the streamed image in sections
        for block in response.iter_content(1024 * 8):
            
            # If no more file then stop
            if not block:
                break
    
            # Write image block to temporary file
            lf.write(block)
    
        # Create the model you want to save the image to
        image = Image()
    
        # Save the temporary image to the model#
        # This saves the model so be sure that it is valid
        image.image.save(file_name, files.File(lf))
    

    Some reference links:

    1. requests - "HTTP for Humans", I prefer this to urllib2
    2. tempfile - Save temporay file and not to disk
    3. Django filefield save

提交回复
热议问题