Skip to content

wsgiref.headers.Headers.__setitem__ deletes the old header before validating the new value #158225

Description

@Tony123-tech

In Lib/wsgiref/headers.py, Headers.setitem deletes the existing
header before validating the new name and value:

def __setitem__(self, name, val):
    """Set the value of a header."""
    del self[name]
    self._headers.append(
        (self._convert_string_type(name, name=True),
         self._convert_string_type(val, name=False)))

If _convert_string_type raises (for example when val is not a string),
the old header has already been removed and the new one is never added,
so the header disappears entirely.

Reproduction:

from wsgiref.headers import Headers
h = Headers([("Content-Type", "text/html")])
try:
    h["Content-Type"] = 123
except AssertionError:
    pass
print(h.get("Content-Type"))
# Expected: 'text/html'
# Actual: None

The fix is to validate the new name and value before deleting the old
header.

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions