mimesniff

raw JSON →
1.1.1 verified Fri May 01 auth: no python

A pure Python implementation of the MIME sniffing algorithm from the WHATWG MIME Sniffing specification. Version 1.1.1 supports Python >=3.4 and allows sniffing MIME types from file-like objects or pre-read headers. Uses a decision tree based on byte patterns. Released infrequently.

pip install mimesniff
error TypeError: a bytes-like object is required, not 'str'
cause Passing a string (text) to sniff() instead of bytes.
fix
Encode the string to bytes: sniff(my_string.encode('utf-8'))
error ImportError: cannot import name 'sniffer' from 'mimesniff'
cause Trying to import from a submodule that doesn't exist (e.g., from mimesniff.sniffer import sniff).
fix
Use 'from mimesniff import sniff'.
gotcha sniff() expects bytes or a binary file-like object. Passing a string or text mode file will raise TypeError or produce incorrect results.
fix Open files in binary mode (e.g., open('file', 'rb')) and ensure input is bytes.
gotcha MimeSniffer class is partially implemented; sniff() function is the recommended entry point. The class API may change in future versions.
fix Use sniff() function for stability.
deprecated The 'PathLike' support was removed in version 1.0.1 for Python 3.4 compatibility. Using pathlib.Path objects may fail.
fix Read the file bytes manually before passing to sniff().

Call sniff() with bytes or a file-like object (opened in binary mode) to get the sniffed MIME type as a string.

import io
from mimesniff import sniff

# Example from bytes
mime_type = sniff(b'%PDF-1.4')
print(mime_type)  # application/pdf

# Example from file-like object
with open('example.html', 'rb') as f:
    mime_type = sniff(f)
    print(mime_type)  # text/html