datastructures.py
This file
Path
httpcore/datastructures.py
145 lines · 4.0 KiB · Python
Last changed by
ConnectionsTom Christiebefore adoption86263fa
History of this fileTake it
ConnectionsTom Christiebefore adoption86263fa
lines 1–145why, one step back1import typing2from urllib.parse import urlsplit34from .decoders import IdentityDecoder5from .exceptions import ResponseClosed, StreamConsumed678class URL:9 def __init__(self, url: str = "") -> None:10 self.components = urlsplit(url)11 if not self.components.scheme:12 raise ValueError("No scheme included in URL.")13 if self.components.scheme not in ("http", "https"):14 raise ValueError('URL scheme must be "http" or "https".')15 if not self.components.hostname:16 raise ValueError("No hostname included in URL.")1718 @property19 def scheme(self) -> str:20 return self.components.scheme2122 @property23 def netloc(self) -> str:24 return self.components.netloc2526 @property27 def path(self) -> str:28 return self.components.path2930 @property31 def query(self) -> str:32 return self.components.query3334 @property35 def hostname(self) -> str:36 return self.components.hostname3738 @property39 def port(self) -> int:40 port = self.components.port41 if port is None:42 return {"https": 443, "http": 80}[self.scheme]43 return port4445 @property46 def target(self) -> str:47 path = self.path or "/"48 query = self.query49 if query:50 return path + "?" + query51 return path5253 @property54 def is_secure(self) -> bool:55 return self.components.scheme == "https"565758class Request:59 def __init__(60 self,61 method: str,62 url: URL,63 *,64 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66 ):67 self.method = method68 self.url = url69 self.headers = list(headers)70 if isinstance(body, bytes):71 self.is_streaming = False72 self.body = body73 else:74 self.is_streaming = True75 self.body_aiter = body7677 async def stream(self) -> typing.AsyncIterator[bytes]:78 assert self.is_streaming7980 async for part in self.body_aiter:81 yield part828384class Response:85 def __init__(86 self,87 status_code: int,88 *,89 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),90 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",91 on_close: typing.Callable = None,92 ):93 self.status_code = status_code94 self.headers = list(headers)95 self.on_close = on_close96 self.is_closed = False97 self.is_streamed = False98 self.decoder = IdentityDecoder()99 if isinstance(body, bytes):100 self.is_closed = True101 self.body = body102 else:103 self.body_aiter = body104105 async def read(self) -> bytes:106 """107 Read and return the response content.108 """109 if not hasattr(self, "body"):110 body = b""111 async for part in self.stream():112 body += part113 self.body = body114 return self.body115116 async def stream(self) -> typing.AsyncIterator[bytes]:117 """118 A byte-iterator over the decoded response content.119 This will allow us to handle gzip, deflate, and brotli encoded responses.120 """121 if hasattr(self, "body"):122 yield self.body123 else:124 async for chunk in self.raw():125 yield self.decoder.decode(chunk)126 yield self.decoder.flush()127128 async def raw(self) -> typing.AsyncIterator[bytes]:129 """130 A byte-iterator over the raw response content.131 """132 if self.is_streamed:133 raise StreamConsumed()134 if self.is_closed:135 raise ResponseClosed()136 self.is_streamed = True137 async for part in self.body_aiter:138 yield part139 await self.close()140141 async def close(self) -> None:142 if not self.is_closed:143 self.is_closed = True144 if self.on_close is not None:145 await self.on_close()