About Checking MIME Types

You can check the MIME type of a file using the built-in mimetypes module, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import os
import mimetypes
from django.http.response import HttpResponse
from django.conf import settings

def serve_file(request, path):
    # TODO: add any security measures here…
    absolute_path = os.path.join(settings.STATIC_ROOT, path)
    file_name = path.rsplit("/", 1)[-1]
    mime_type, encoding = mimetypes.guess_type(absolute_path)
    the_file = open(absolute_path, "rb")
    response = HttpResponse(content=the_file)
    response["Content-Type"] = mime_type
    response["Content-Disposition"] = f'inline; filename="{file_name}"'
    return response

Tips and Tricks Programming Django 2.2 Django 1.11 Django 1.8 Python 3