Python-MimeParse
Python-MimeParse is a stable and mature project that provides basic functions for parsing MIME type names and matching them against a list of media ranges, adhering to HTTP specifications. The current version is 2.0.0, which includes support for CPython 3.13 and drops support for Python 3.7. The project aims for stability with infrequent, but significant, updates.
Warnings
- breaking Version 2.0.0 dropped official support for Python 3.7. Users on Python 3.7 or older must remain on python-mimeparse 1.x.
- gotcha There is an older, unmaintained package named `mimeparse` on PyPI (last updated 2013). Ensure you install `python-mimeparse` to get the actively maintained version.
- gotcha Behavior related to `q` (quality) parameters in media ranges (e.g., in `Accept` headers) was significantly enhanced in version 1.6.0. Upgrading from versions prior to 1.6.0 might result in different `best_match` or `quality` outcomes for complex media range comparisons due to more accurate RFC compliance.
- breaking Version 2.0.0 internally addressed the deprecation and removal of the `cgi` module in Python 3.13 by vendoring necessary functions. While this prevents a future runtime error for users, it represents a significant internal compatibility overhaul for Python versions beyond 3.11.
Install
-
pip install python-mimeparse
Imports
- parse_mime_type
from mimeparse import parse_mime_type
- parse_media_range
from mimeparse import parse_media_range
- quality
from mimeparse import quality
- quality_parsed
from mimeparse import quality_parsed
- best_match
from mimeparse import best_match
Quickstart
from mimeparse import best_match
supported_types = ['application/json', 'text/html', 'image/jpeg', 'text/plain']
accept_header = 'text/*;q=0.5, application/json;q=1.0, */*;q=0.8'
match = best_match(supported_types, accept_header)
print(f"Best match for '{accept_header}' from supported types: {match}")
# Example with parsing a specific mime type
from mimeparse import parse_mime_type
mime_type = 'application/json; charset=utf-8'
parsed_type = parse_mime_type(mime_type)
print(f"Parsed '{mime_type}': {parsed_type}")