From 5427072b12119fe28fd66f19f74beb7da0c1de8b Mon Sep 17 00:00:00 2001 From: Stanis Trendelenburg Date: Mon, 1 Jan 2024 12:48:19 +0100 Subject: [PATCH] chore(cgi): include `parse_header()` from the deprecated cgi module (#46) * Include functions from the deprecated cgi module * Document source of vendored functions from cgi.py * Fix linter error --- Upstream-PR: https://github.com/falconry/python-mimeparse/pull/46 diff --git a/mimeparse.py b/mimeparse.py index 0de6d57..506e138 100644 --- a/mimeparse.py +++ b/mimeparse.py @@ -1,5 +1,3 @@ -import cgi - __version__ = '1.6.0' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' @@ -11,6 +9,44 @@ class MimeTypeParseException(ValueError): pass +# Vendored version of cgi._parseparam from Python 3.11 (deprecated and slated +# for removal in 3.13) +def _parseparam(s): + while s[:1] == ';': + s = s[1:] + end = s.find(';') + while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: + end = s.find(';', end + 1) + if end < 0: + end = len(s) + f = s[:end] + yield f.strip() + s = s[end:] + + +# Vendored version of cgi.parse_header from Python 3.11 (deprecated and slated +# for removal in 3.13) +def _parse_header(line): + """Parse a Content-type like header. + + Return the main content-type and a dictionary of options. + + """ + parts = _parseparam(';' + line) + key = parts.__next__() + pdict = {} + for p in parts: + i = p.find('=') + if i >= 0: + name = p[:i].strip().lower() + value = p[i + 1:].strip() + if len(value) >= 2 and value[0] == value[-1] == '"': + value = value[1:-1] + value = value.replace('\\\\', '\\').replace('\\"', '"') + pdict[name] = value + return key, pdict + + def parse_mime_type(mime_type): """Parses a mime-type into its component parts. @@ -23,7 +59,7 @@ def parse_mime_type(mime_type): :rtype: (str,str,dict) """ - full_type, params = cgi.parse_header(mime_type) + full_type, params = _parse_header(mime_type) # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*':