Skip to content

Instantly share code, notes, and snippets.

@Bogdanp
Created October 17, 2018 05:41
Show Gist options
  • Save Bogdanp/f1eb1265fa64f60aa8dbb19b62e0559d to your computer and use it in GitHub Desktop.
Save Bogdanp/f1eb1265fa64f60aa8dbb19b62e0559d to your computer and use it in GitHub Desktop.
class Request(typing.NamedTuple):
method: str
path: str
headers: typing.Mapping[str, str]
@classmethod
def from_socket(cls, sock: socket.socket) -> "Request":
"""Read and parse the request from a socket object.
Raises:
ValueError: When the request cannot be parsed.
"""
lines = iter_lines(sock)
try:
request_line = next(lines).decode("ascii")
except StopIteration:
raise ValueError("Request line missing.")
try:
method, path, _ = request_line.split(" ")
except ValueError:
raise ValueError(f"Malformed request line {request_line!r}.")
headers = {}
for line in lines:
try:
name, _, value = line.decode("ascii").partition(":")
headers[name.lower()] = value.lstrip()
except ValueError:
raise ValueError(f"Malformed header line {line!r}.")
return cls(method=method.upper(), path=path, headers=headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment