About Checking File Types of Remote Files

You can check the file type of a remote file using the requests and filetype libraries:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import requests
import filetype
from django.core.files.uploadedfile import SimpleUploadedFile

response = requests.get("https://example.com/logo12345")
if response.status_code == requests.codes.OK:
    kind = filetype.guess(response.content)
    logo = Logo.objects.create(
        image=SimpleUploadedFile(
            name=f"logo.{kind.extension}",
            content=response.content,
            content_type=kind.mime,
        ),
    )

Tips and Tricks Programming Python 3 requests