Read a Location header from a local response
Also published in our primary archive.
A redirect-aware program often needs to read Location before deciding whether to resolve or follow the target. This example keeps a synthetic 302 Found response entirely in BytesIO. It separates the status line, parses only the following headers with BytesHeaderParser, and reads Location through the parsed message. The exact value is ../signin?continue=/docs; the assertion deliberately preserves it as a relative reference rather than converting it into a URL.
The email.parser documentation describes BytesHeaderParser for byte input containing headers only, and the email.message documentation documents message header access. This is a compact fixture parser, not a general HTTP client: it uses the compatible header-field form to inspect known local bytes and does not open a connection.
Keeping the original header value matters because resolving a relative location requires the URL of the request that produced it. That context is intentionally absent here. The assertions show that this particular header block exposes one exact value; they do not establish that a redirect is safe to follow or valid for every response. Production code should explicitly choose behavior for missing, repeated, malformed, or disallowed locations before any navigation. BytesHeaderParser was added in Python 3.3. AI assistance was used to draft this article.
from email.parser import BytesHeaderParser
from io import BytesIO
raw_response = (
b"HTTP/1.1 302 Found\r\n"
b"Location: ../signin?continue=/docs\r\n"
b"Content-Length: 0\r\n"
b"\r\n"
)
stream = BytesIO(raw_response)
status_line = stream.readline().decode("ascii").rstrip("\r\n")
headers = BytesHeaderParser().parse(stream)
location = headers["Location"]
assert status_line == "HTTP/1.1 302 Found"
assert location == "../signin?continue=/docs"
print(location)
../signin?continue=/docs