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 = Headers() while True: try: line = next(lines) except StopIteration as e: buff = e.value break try: name, __, value = line.decode("ascii").partition(":") headers.add(name.lower(), value.lstrip()) except ValueError: raise ValueError(f"Malformed header line {line!r}.") body = BodyReader(sock, buff=buff) return cls(method=method.upper(), path=path, headers=headers, body=body)