On this page
  1. mimetypes
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Computing Safe Content-Type Headers with Fallback
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

mimetypes

Prev: math | Up: stdlib_module | Next: mmap
Rel: email, json, mailbox, base64, binascii
Ref: docs.python.org — mimetypes
Tags: #public #python3 #stdlib


Import

import mimetypes

Overview

Maps filename extensions to IANA MIME types (guess_type, guess_file_type, guess_extension, add_type). Essential for HTTP static file servers, email attachments, and upload handlers needing accurate Content-Type headers without hardcoding extension tables.

Quick Start

import mimetypes

mime, encoding = mimetypes.guess_type("report.json")
assert mime == "application/json" and encoding is None

ext = mimetypes.guess_extension("text/markdown")
assert ext in {".md", ".markdown"}

Implementation Walkthrough

1. Computing Safe Content-Type Headers with Fallback

import mimetypes
from pathlib import Path

def content_type_for(path: Path) -> str:
    mime, _ = mimetypes.guess_type(path.name)
    if mime is None:
        return "application/octet-stream"
    if mime.startswith("text/") or mime in {"application/json", "application/javascript"}:
        return f"{mime}; charset=utf-8"
    return mime

assert content_type_for(Path("style.css")) == "text/css; charset=utf-8"
assert content_type_for(Path("blob.unknownext")) == "application/octet-stream"

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes