Skip to content

k3mime

Action-CI Documentation Status Package

MIME type detection by filename. Returns the correct MIME type based on file extension.

k3mime is a component of pykit3 project: a python3 toolkit set.

Installation

pip install k3mime

Quick Start

from k3mime import get_by_filename

# Get MIME type by filename
print(get_by_filename("document.pdf"))  # application/pdf
print(get_by_filename("image.png"))     # image/png
print(get_by_filename("video.mp4"))     # video/mp4
print(get_by_filename("data.json"))     # application/json

# Unknown extensions return application/octet-stream
print(get_by_filename("unknown.xyz"))   # application/octet-stream

API Reference

k3mime

get_by_filename(filename)

Return mime type according to filename suffix.

:param filename: is a string. :return: mime type that predefined.

Source code in k3mime/mime.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def get_by_filename(filename):
    """
    Return mime type according to filename suffix.

    :param filename: is a string.
    :return: mime type that predefined.
    """

    mime_type = None

    if filename.find(".") != -1:
        suffix = filename.rsplit(".", 1)[-1]
        mime_type = mimes.get(suffix)
        if mime_type is None:
            mime_type, _ = mimetypes.guess_type(filename)

    return mime_type or OCTET_STREAM

License

The MIT License (MIT) - Copyright (c) 2015 Zhang Yanpo (张炎泼)