More specific naming: mime is simple str, media_type may have q and raw is header component.

This commit is contained in:
L. Karkkainen 2023-02-05 16:25:20 +00:00
parent 2e2231919c
commit 6472a69fbf

View File

@ -54,18 +54,22 @@ class MediaType:
self.subtype = subtype self.subtype = subtype
self.q = float(params.get("q", "1.0")) self.q = float(params.get("q", "1.0"))
self.params = params self.params = params
self.str = f"{type_}/{subtype}" self.mime = f"{type_}/{subtype}"
def __repr__(self): def __repr__(self):
return self.str + "".join(f";{k}={v}" for k, v in self.params.items()) return self.mime + "".join(f";{k}={v}" for k, v in self.params.items())
def __eq__(self, media_type: str): def __eq__(self, other):
"""Check if the type and subtype match exactly.""" """Check for mime (str or MediaType) identical type/subtype."""
return self.str == media_type if isinstance(other, str):
return self.mime == other
if isinstance(other, MediaType):
return self.mime == other.mime
return NotImplemented
def match( def match(
self, self,
media_type: str, mime: str,
allow_type_wildcard=True, allow_type_wildcard=True,
allow_subtype_wildcard=True, allow_subtype_wildcard=True,
) -> Optional[MediaType]: ) -> Optional[MediaType]:
@ -79,12 +83,13 @@ class MediaType:
@param media_type: A type/subtype string to match. @param media_type: A type/subtype string to match.
@return `self` if the media types are compatible, else `None` @return `self` if the media types are compatible, else `None`
""" """
mt = MediaType._parse(media_type) mt = MediaType._parse(mime)
return self if ( return self if (
# Subtype match # Subtype match
(self.subtype in (mt.subtype, "*") or mt.subtype == "*") (self.subtype in (mt.subtype, "*") or mt.subtype == "*")
# Type match # Type match
and (self.type_ in (mt.type_, "*") or mt.type_ == "*") and (self.type_ in (mt.type_, "*") or mt.type_ == "*")
# Allow disabling wildcards (backwards compatibility with tests)
and (allow_type_wildcard or self.type_ != "*" and mt.type_ != "*") and (allow_type_wildcard or self.type_ != "*" and mt.type_ != "*")
and (allow_subtype_wildcard or self.subtype != "*" and mt.subtype != "*") and (allow_subtype_wildcard or self.subtype != "*" and mt.subtype != "*")
) else None ) else None
@ -100,8 +105,8 @@ class MediaType:
return self.type_ == "*" and self.subtype == "*" return self.type_ == "*" and self.subtype == "*"
@classmethod @classmethod
def _parse(cls, raw: str) -> MediaType: def _parse(cls, mime_with_params: str) -> MediaType:
mtype = raw.strip() mtype = mime_with_params.strip()
media, *raw_params = mtype.split(";") media, *raw_params = mtype.split(";")
type_, subtype = media.split("/", 1) type_, subtype = media.split("/", 1)