Skip to main content

mediaparse

Lianes8 Certified

Parse and build HTTP media types, Content-Type and Accept headers, exactly.

Install

pip install mediaparse

Usage

from mediaparse import build, matches, normalize, parse, parse_media_type

# Read a Content-Type value the way a browser does.
print(parse("text/html; charset=utf-8"))
# ('text/html', {'charset': 'utf-8'})

# Quoted values keep separators; text after the closing quote is skipped.
print(parse('multipart/form-data; boundary="a; b=c"'))
# ('multipart/form-data', {'boundary': 'a; b=c'})

# A typed value with the essence, the +suffix and the browser serialization.
media = parse_media_type("Application/Vnd.API+JSON; Charset=UTF-8")
print(media.essence, media.suffix, media.get("charset"))
# application/vnd.api+json json UTF-8
print(media)
# application/vnd.api+json;charset=UTF-8

# Build a header, quoting only the values that need it.
print(build("application/json", {"title": "a; b"}))
# application/json; title="a; b"

# Canonical form for display or comparison.
print(normalize("TEXT/HTML; CharSet=UTF-8"))
# text/html; charset=utf-8
print(matches("Text/HTML; charset=UTF-8", "text/html;charset=utf-8"))
# True

Lenient or strict

from mediaparse import MediaTypeError, parse

# Default: the WHATWG algorithm. The first of a repeated parameter wins and a parameter
# with whitespace before "=" is skipped, exactly as browsers do.
print(parse("text/plain; charset=ascii; charset=utf-8; a =1"))
# ('text/plain', {'charset': 'ascii'})

# strict=True: the RFC 9110 grammar, with the position of the first bad character.
try:
    parse("text/plain; a =1", strict=True)
except MediaTypeError as error:
    print(error.position)
# 13

Building safely

from mediaparse import MediaTypeError, build

# No value can split the header: control characters are refused.
try:
    build("text/plain", {"name": "x\r\nSet-Cookie: a=b"})
except MediaTypeError:
    print("refused")
# refused

# Non-ASCII values travel as RFC 8187 / RFC 2231 extended values on request.
print(build("text/plain", {"title": "caf\xe9"}, extended=True))
# text/plain; title*=UTF-8''caf%C3%A9

Accept and negotiation

from mediaparse import negotiate, parse_accept, quality

accept = "text/*;q=0.3, text/plain;q=0.7, text/plain;format=flowed, */*;q=0.5"

# The weight comes from the most specific range that covers the offer.
print(quality(accept, "text/plain;format=flowed"), quality(accept, "text/html"))
# 1.0 0.3

# Pick the best offer; ties go to the order you list them in.
print(negotiate(accept, ["image/png", "text/html"]))
# image/png

print([(str(item.media_range), item.q) for item in parse_accept("text/html, */*;q=0.1")])
# [('text/html', 1.0), ('*/*', 0.1)]

RFC 2231 parameters

from mediaparse import decode_extended, parse

header = "application/x-stuff; title*0*=utf-8''r%C3%A9sum; title*1=\"e.pdf\""
print(decode_extended(parse(header)[1]))
# {'title': 'résume.pdf'}

API

Name What it does
parse(header, *, strict=False) (essence, params) tuple.
parse_media_type(text, *, strict=False) A MediaType; raises MediaTypeError when there is no valid type/subtype.
MediaType Frozen value: type, subtype, params pairs, essence, suffix, parameters, get(), str().
build(mimetype, params=None, *, extended=False) Header value with "; " between parts and minimal quoting.
normalize(header, *, strict=False) Lower-cased names, sorted parameters, lower-cased charset.
matches(first, second) Whether two headers normalize to the same text.
parse_accept(header, *, strict=False) List of AcceptItem in header order.
AcceptItem media_range (a MediaType), q (0 to 1), specificity(), matches(media).
quality(accept, offer) Weight of an offer under an Accept header; None means no header.
negotiate(accept, offers) Best acceptable offer, returned as given, or None.
decode_extended(params) Joins RFC 2231 sections and decodes charset'lang' values.
MediaTypeError ValueError subclass with position (or None). Wrong argument types raise TypeError.

Rules it follows

The default mode is the WHATWG MIME Sniffing algorithm, what browsers do; strict=True is the RFC 9110 grammar exactly. Building never writes a character that could split the header. The GUIDE has every rule in detail, and the CHANGELOG what changed in each release.

Why

Python 3.13 removed cgi.parse_header along with the rest of the cgi module. The email.message.Message machinery that replaces it is built for mail: it reads a quoted value ending in an escaped backslash (x="a\\") past its closing quote, and its set_param on its default policy stores a CR LF from a value in the header. multipart.parse_options_header drops parameters whose names hold characters other than letters, digits, - and _, and werkzeug is a whole WSGI application library. mediaparse is a small, typed, zero-dependency library that parses the way browsers do, validates the way the RFC says, builds headers that cannot be split, and negotiates Accept. It is tested against the specifications themselves, the IANA registry and those parsers.

Development

python scripts/fetch_upstream.py downloads the specifications, registries and web-platform-tests files listed in tests/upstream/MANIFEST.json (they are not part of the repository; their tests skip without them). pip install werkzeug multipart and npm install --prefix tests/upstream whatwg-mimetype@5.0.0 add the reference parsers. scripts/check.ps1 runs format, lint, types and tests. Set MEDIAPARSE_E2E=1 to also build the wheel and test the installed package.

License

MIT. See LICENSE.

Metadata

Release files for mediaparse 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mediaparse 1.0.0
File Size Uploaded Provenance Actions
mediaparse-1.0.0.tar.gz 57.3 kB Without provenance Details for mediaparse-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mediaparse 1.0.0
File Interpreter ABI Platform Actions
mediaparse-1.0.0-py3-none-any.whl Python 3 none any Details for mediaparse-1.0.0-py3-none-any.whl

Total release size: 81.3 kB

Release files / mediaparse-1.0.0.tar.gz

Download URL mediaparse-1.0.0.tar.gz
Size 57.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9feb078e17ea7388d8702659604bb771b6f46ac6e0fd8f2c6f68edb2ca20f660
BLAKE2b-256 checksum
How to use checksums
8add7a5f505d5d5fa915b6a0c3de4ed5f2bbad149fa430cfacd3d3168a0e8905
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release files / mediaparse-1.0.0-py3-none-any.whl

Download URL mediaparse-1.0.0-py3-none-any.whl
Size 24.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
39ab65c6a47716cc81360570f19ffbdd4a8b0d4a23c644f1b328f92c91e3d01a
BLAKE2b-256 checksum
How to use checksums
1fbd75de51585573fa05b783bf3f2d91a69a023c1c91863fc4d163df2725dfcb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Security for mediaparse 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page