Skip to content

Commit

Permalink
Replace the cgi module by vendoring used functions
Browse files Browse the repository at this point in the history
Python 3.13 dropped the deprecated cgi module. Remove the module and
include the relevant function to parse the content header.
  • Loading branch information
timhallmann committed Feb 14, 2025
1 parent f6b3ac0 commit 3b952d8
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/simple_openid_connect/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""
Internal utilities
"""
import cgi

from typing import Iterator

from simple_openid_connect.exceptions import ValidationError

Expand All @@ -11,7 +12,7 @@ def is_application_json(content_type: str) -> bool:
Whether the given content type is `application/json`.
This is needed because mime types can contain additional options which are ignored here.
"""
main_type, _options = cgi.parse_header(content_type)
main_type = _parse_header(content_type)
return main_type == "application/json"


Expand All @@ -25,3 +26,28 @@ def validate_that(condition: bool, msg: str) -> None:
"""
if not condition:
raise ValidationError(msg)


def _parse_header(line: str) -> str:
"""Parse a Content-type like header.
Return the main content-type.
"""
# Adapted from https://github.com/python/cpython/blob/3.12/Lib/cgi.py#L238
# by adding type hints and removing the parsing of additional mime type options.
return _parseparam(";" + line).__next__()


def _parseparam(s: str) -> Iterator[str]:
# Adapted from https://github.com/python/cpython/blob/3.12/Lib/cgi.py#L226
# by adding type hints.
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:]

0 comments on commit 3b952d8

Please sign in to comment.