Skip to content
Myr

Add stream ID to HTTP2Connection

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by Tom Christie · parent 53f3dc4 · Browse files · 9 files+459 added−464 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+459 added−464 removed

  • other:+459 added−464 removed

9 files+459 added−464 removed

modified:httpcore/__init__.py+2 added-2 removed
1from .config import PoolLimits, SSLConfig, TimeoutConfig2from .connection import HTTPConnection3from .connectionpool import ConnectionPool4from .datastructures import URL, Origin, Request, Response3from .connection_pool import ConnectionPool4from .exceptions import (5 ConnectTimeout,6 PoolTimeout,7 ProtocolError,
3 unmodified lines
11 Timeout,12)13from .http2 import HTTP2Connection14from .http11 import HTTP11Connection15from .models import URL, Origin, Request, Response16from .sync import SyncClient, SyncConnectionPool1718__version__ = "0.2.1"
added:httpcore/connection_pool.py+132 added
1import asyncio2import typing34from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,8 DEFAULT_TIMEOUT_CONFIG,9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .connection import HTTPConnection14from .exceptions import PoolTimeout15from .models import Client, Origin, Request, Response161718class ConnectionPool(Client):19 def __init__(20 self,21 *,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24 limits: PoolLimits = DEFAULT_POOL_LIMITS,25 ):26 self.ssl = ssl27 self.timeout = timeout28 self.limits = limits29 self.is_closed = False30 self.num_active_connections = 031 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}34 ) # type: typing.Dict[Origin, typing.List[HTTPConnection]]35 self._max_connections = ConnectionSemaphore(36 max_connections=self.limits.hard_limit37 )3839 async def send(40 self,41 request: Request,42 *,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None,45 ) -> Response:46 connection = await self.acquire_connection(request.url.origin, timeout=timeout)47 response = await connection.send(request, ssl=ssl, timeout=timeout)48 return response4950 @property51 def num_connections(self) -> int:52 return self.num_active_connections + self.num_keepalive_connections5354 async def acquire_connection(55 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56 ) -> HTTPConnection:57 try:58 connection = self._keepalive_connections[origin].pop()59 if not self._keepalive_connections[origin]:60 del self._keepalive_connections[origin]61 self.num_keepalive_connections -= 162 self.num_active_connections += 16364 except (KeyError, IndexError):65 if timeout is None:66 pool_timeout = self.timeout.pool_timeout67 else:68 pool_timeout = timeout.pool_timeout6970 try:71 await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72 except asyncio.TimeoutError:73 raise PoolTimeout()74 connection = HTTPConnection(75 origin,76 ssl=self.ssl,77 timeout=self.timeout,78 on_release=self.release_connection,79 )80 self.num_active_connections += 18182 return connection8384 async def release_connection(self, connection: HTTPConnection) -> None:85 if connection.is_closed:86 self._max_connections.release()87 self.num_active_connections -= 188 elif (89 self.limits.soft_limit is not None90 and self.num_connections > self.limits.soft_limit91 ):92 self._max_connections.release()93 self.num_active_connections -= 194 await connection.close()95 else:96 self.num_active_connections -= 197 self.num_keepalive_connections += 198 try:99 self._keepalive_connections[connection.origin].append(connection)100 except KeyError:101 self._keepalive_connections[connection.origin] = [connection]102103 async def close(self) -> None:104 self.is_closed = True105 all_connections = []106 for connections in self._keepalive_connections.values():107 all_connections.extend(list(connections))108 self._keepalive_connections.clear()109 for connection in all_connections:110 await connection.close()111112113class ConnectionSemaphore:114 def __init__(self, max_connections: int = None):115 self.max_connections = max_connections116117 @property118 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:119 if not hasattr(self, "_semaphore"):120 if self.max_connections is None:121 self._semaphore = None122 else:123 self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)124 return self._semaphore125126 async def acquire(self) -> None:127 if self.semaphore is not None:128 await self.semaphore.acquire()129130 def release(self) -> None:131 if self.semaphore is not None:132 self.semaphore.release()
modified:httpcore/connection.py+1 added-1 removed
3 unmodified lines
4import h2.connection5import h1167from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig8from .datastructures import Client, Origin, Request, Response8from .exceptions import ConnectTimeout9from .http2 import HTTP2Connection10from .http11 import HTTP11Connection11from .models import Client, Origin, Request, Response121314class HTTPConnection(Client):15 def __init__(
91 unmodified lines
deleted:httpcore/connectionpool.py-132 removed
1import asyncio2import typing34from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,8 DEFAULT_TIMEOUT_CONFIG,9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .connection import HTTPConnection14from .datastructures import Client, Origin, Request, Response15from .exceptions import PoolTimeout161718class ConnectionPool(Client):19 def __init__(20 self,21 *,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24 limits: PoolLimits = DEFAULT_POOL_LIMITS,25 ):26 self.ssl = ssl27 self.timeout = timeout28 self.limits = limits29 self.is_closed = False30 self.num_active_connections = 031 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}34 ) # type: typing.Dict[Origin, typing.List[HTTPConnection]]35 self._max_connections = ConnectionSemaphore(36 max_connections=self.limits.hard_limit37 )3839 async def send(40 self,41 request: Request,42 *,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None,45 ) -> Response:46 connection = await self.acquire_connection(request.url.origin, timeout=timeout)47 response = await connection.send(request, ssl=ssl, timeout=timeout)48 return response4950 @property51 def num_connections(self) -> int:52 return self.num_active_connections + self.num_keepalive_connections5354 async def acquire_connection(55 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56 ) -> HTTPConnection:57 try:58 connection = self._keepalive_connections[origin].pop()59 if not self._keepalive_connections[origin]:60 del self._keepalive_connections[origin]61 self.num_keepalive_connections -= 162 self.num_active_connections += 16364 except (KeyError, IndexError):65 if timeout is None:66 pool_timeout = self.timeout.pool_timeout67 else:68 pool_timeout = timeout.pool_timeout6970 try:71 await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72 except asyncio.TimeoutError:73 raise PoolTimeout()74 connection = HTTPConnection(75 origin,76 ssl=self.ssl,77 timeout=self.timeout,78 on_release=self.release_connection,79 )80 self.num_active_connections += 18182 return connection8384 async def release_connection(self, connection: HTTPConnection) -> None:85 if connection.is_closed:86 self._max_connections.release()87 self.num_active_connections -= 188 elif (89 self.limits.soft_limit is not None90 and self.num_connections > self.limits.soft_limit91 ):92 self._max_connections.release()93 self.num_active_connections -= 194 await connection.close()95 else:96 self.num_active_connections -= 197 self.num_keepalive_connections += 198 try:99 self._keepalive_connections[connection.origin].append(connection)100 except KeyError:101 self._keepalive_connections[connection.origin] = [connection]102103 async def close(self) -> None:104 self.is_closed = True105 all_connections = []106 for connections in self._keepalive_connections.values():107 all_connections.extend(list(connections))108 self._keepalive_connections.clear()109 for connection in all_connections:110 await connection.close()111112113class ConnectionSemaphore:114 def __init__(self, max_connections: int = None):115 self.max_connections = max_connections116117 @property118 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:119 if not hasattr(self, "_semaphore"):120 if self.max_connections is None:121 self._semaphore = None122 else:123 self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)124 return self._semaphore125126 async def acquire(self) -> None:127 if self.semaphore is not None:128 await self.semaphore.acquire()129130 def release(self) -> None:131 if self.semaphore is not None:132 self.semaphore.release()
deleted:httpcore/datastructures.py-283 removed
1import http2import typing3from types import TracebackType4from urllib.parse import urlsplit56from .config import SSLConfig, TimeoutConfig7from .decoders import (8 ACCEPT_ENCODING,9 SUPPORTED_DECODERS,10 Decoder,11 IdentityDecoder,12 MultiDecoder,13)14from .exceptions import ResponseClosed, StreamConsumed151617class URL:18 def __init__(self, url: str = "") -> None:19 self.components = urlsplit(url)20 if not self.components.scheme:21 raise ValueError("No scheme included in URL.")22 if self.components.scheme not in ("http", "https"):23 raise ValueError('URL scheme must be "http" or "https".')24 if not self.components.hostname:25 raise ValueError("No hostname included in URL.")2627 @property28 def scheme(self) -> str:29 return self.components.scheme3031 @property32 def netloc(self) -> str:33 return self.components.netloc3435 @property36 def path(self) -> str:37 return self.components.path3839 @property40 def query(self) -> str:41 return self.components.query4243 @property44 def hostname(self) -> str:45 return self.components.hostname4647 @property48 def port(self) -> int:49 port = self.components.port50 if port is None:51 return {"https": 443, "http": 80}[self.scheme]52 return port5354 @property55 def full_path(self) -> str:56 path = self.path or "/"57 query = self.query58 if query:59 return path + "?" + query60 return path6162 @property63 def is_secure(self) -> bool:64 return self.components.scheme == "https"6566 @property67 def origin(self) -> "Origin":68 return Origin(self)697071class Origin:72 def __init__(self, url: typing.Union[str, URL]) -> None:73 if isinstance(url, str):74 url = URL(url)75 self.is_ssl = url.scheme == "https"76 self.hostname = url.hostname.lower()77 self.port = url.port7879 def __eq__(self, other: typing.Any) -> bool:80 return (81 isinstance(other, self.__class__)82 and self.is_ssl == other.is_ssl83 and self.hostname == other.hostname84 and self.port == other.port85 )8687 def __hash__(self) -> int:88 return hash((self.is_ssl, self.hostname, self.port))899091class Request:92 def __init__(93 self,94 method: str,95 url: typing.Union[str, URL],96 *,97 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),98 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",99 ):100 self.method = method.upper()101 self.url = URL(url) if isinstance(url, str) else url102 self.headers = list(headers)103 if isinstance(body, bytes):104 self.is_streaming = False105 self.body = body106 else:107 self.is_streaming = True108 self.body_aiter = body109 self.headers = self._auto_headers() + self.headers110111 def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:112 has_host = False113 has_content_length = False114 has_accept_encoding = False115116 for header, value in self.headers:117 header = header.strip().lower()118 if header == b"host":119 has_host = True120 elif header in (b"content-length", b"transfer-encoding"):121 has_content_length = True122 elif header == b"accept-encoding":123 has_accept_encoding = True124125 headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]126127 if not has_host:128 headers.append((b"host", self.url.netloc.encode("ascii")))129 if not has_content_length:130 if self.is_streaming:131 headers.append((b"transfer-encoding", b"chunked"))132 elif self.body:133 content_length = str(len(self.body)).encode()134 headers.append((b"content-length", content_length))135 if not has_accept_encoding:136 headers.append((b"accept-encoding", ACCEPT_ENCODING))137138 return headers139140 async def stream(self) -> typing.AsyncIterator[bytes]:141 if self.is_streaming:142 async for part in self.body_aiter:143 yield part144 elif self.body:145 yield self.body146147148class Response:149 def __init__(150 self,151 status_code: int,152 *,153 reason: typing.Optional[str] = None,154 protocol: typing.Optional[str] = None,155 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),156 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",157 on_close: typing.Callable = None,158 ):159 self.status_code = status_code160 if not reason:161 try:162 self.reason = http.HTTPStatus(status_code).phrase163 except ValueError as exc:164 self.reason = ""165 else:166 self.reason = reason167 self.protocol = protocol168 self.headers = list(headers)169 self.on_close = on_close170 self.is_closed = False171 self.is_streamed = False172173 decoders = [] # type: typing.List[Decoder]174 for header, value in self.headers:175 if header.strip().lower() == b"content-encoding":176 for part in value.split(b","):177 part = part.strip().lower()178 decoder_cls = SUPPORTED_DECODERS[part]179 decoders.append(decoder_cls())180181 if len(decoders) == 0:182 self.decoder = IdentityDecoder() # type: Decoder183 elif len(decoders) == 1:184 self.decoder = decoders[0]185 else:186 self.decoder = MultiDecoder(decoders)187188 if isinstance(body, bytes):189 self.is_closed = True190 self.body = self.decoder.decode(body) + self.decoder.flush()191 else:192 self.body_aiter = body193194 async def read(self) -> bytes:195 """196 Read and return the response content.197 """198 if not hasattr(self, "body"):199 body = b""200 async for part in self.stream():201 body += part202 self.body = body203 return self.body204205 async def stream(self) -> typing.AsyncIterator[bytes]:206 """207 A byte-iterator over the decoded response content.208 This allows us to handle gzip, deflate, and brotli encoded responses.209 """210 if hasattr(self, "body"):211 yield self.body212 else:213 async for chunk in self.raw():214 yield self.decoder.decode(chunk)215 yield self.decoder.flush()216217 async def raw(self) -> typing.AsyncIterator[bytes]:218 """219 A byte-iterator over the raw response content.220 """221 if self.is_streamed:222 raise StreamConsumed()223 if self.is_closed:224 raise ResponseClosed()225 self.is_streamed = True226 async for part in self.body_aiter:227 yield part228 await self.close()229230 async def close(self) -> None:231 """232 Close the response and release the connection.233 Automatically called if the response body is read to completion.234 """235 if not self.is_closed:236 self.is_closed = True237 if self.on_close is not None:238 await self.on_close()239240241class Client:242 async def request(243 self,244 method: str,245 url: typing.Union[str, URL],246 *,247 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),248 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",249 ssl: typing.Optional[SSLConfig] = None,250 timeout: typing.Optional[TimeoutConfig] = None,251 stream: bool = False,252 ) -> Response:253 request = Request(method, url, headers=headers, body=body)254 response = await self.send(request, ssl=ssl, timeout=timeout)255 if not stream:256 try:257 await response.read()258 finally:259 await response.close()260 return response261262 async def send(263 self,264 request: Request,265 *,266 ssl: typing.Optional[SSLConfig] = None,267 timeout: typing.Optional[TimeoutConfig] = None,268 ) -> Response:269 raise NotImplementedError() # pragma: nocover270271 async def close(self) -> None:272 raise NotImplementedError() # pragma: nocover273274 async def __aenter__(self) -> "Client":275 return self276277 async def __aexit__(278 self,279 exc_type: typing.Type[BaseException] = None,280 exc_value: BaseException = None,281 traceback: TracebackType = None,282 ) -> None:283 await self.close()
modified:httpcore/http11.py+1 added-1 removed
2 unmodified lines
34import h1156from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig7from .datastructures import Client, Origin, Request, Response7from .exceptions import ConnectTimeout, ReadTimeout8from .models import Client, Origin, Request, Response910H11Event = typing.Union[11 h11.Request,12 h11.Response,
123 unmodified lines
modified:httpcore/http2.py+38 added-43 removed
3 unmodified lines
4import h2.connection5import h2.events67from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig8from .datastructures import Client, Origin, Request, Response8from .exceptions import ConnectTimeout, ReadTimeout9from .models import Client, Origin, Request, Response101112class HTTP2Connection(Client):13 def __init__(
9 unmodified lines
23 self.writer = writer24 self.timeout = timeout25 self.on_release = on_release26 self.h2_state = h2.connection.H2Connection()27 self.events = [] # type: typing.List[h2.events.Event]27 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]28 self.initialized = False2930 @property31 def is_closed(self) -> bool:32 return False
7 unmodified lines
40 ) -> Response:41 if timeout is None:42 timeout = self.timeout4344 if not self.initialized:45 self.initiate_connection()4647 #  Start sending the request.44 await self._initiate_connection()45 await self._send_headers(request)48 stream_id = self.h2_state.get_next_available_stream_id()49 self.events[stream_id] = []50 await self.send_headers(stream_id, request)5152 # Send the request body.48 if request.body:49 await self._send_data(request.body)53 async for data in request.stream():54 await self.send_data(stream_id, data)5556 # Finalize sending the request.52 await self._end_stream()57 await self.end_stream(stream_id)5859 # Start getting the response.60 while True:56 event = await self._receive_event(timeout)61 event = await self.receive_event(stream_id, timeout)62 if isinstance(event, h2.events.ResponseReceived):63 break6465 status_code = 200
3 unmodified lines
69 status_code = int(v.decode())70 elif not k.startswith(b":"):71 headers.append((k, v))7268 body = self._body_iter(timeout)73 body = self.body_iter(stream_id, timeout)74 return Response(75 status_code=status_code,76 protocol="HTTP/2",77 headers=headers,78 body=body,74 on_close=self._release,79 on_close=self.release,80 )8177 async def _initiate_connection(self) -> None:82 def initiate_connection(self) -> None:83 self.h2_state.initiate_connection()84 data_to_send = self.h2_state.data_to_send()85 self.writer.write(data_to_send)86 self.initialized = True8782 async def _send_headers(self, request: Request) -> None:88 async def send_headers(self, stream_id: int, request: Request) -> None:89 headers = [90 (b":method", request.method.encode()),91 (b":authority", request.url.hostname.encode()),92 (b":scheme", request.url.scheme.encode()),93 (b":path", request.url.full_path.encode()),94 ] + request.headers89 self.h2_state.send_headers(1, headers)95 self.h2_state.send_headers(stream_id, headers)96 data_to_send = self.h2_state.data_to_send()97 self.writer.write(data_to_send)9893 async def _send_data(self, data: bytes) -> None:94 self.h2_state.send_data(1, data)99 async def send_data(self, stream_id: int, data: bytes) -> None:100 self.h2_state.send_data(stream_id, data)101 data_to_send = self.h2_state.data_to_send()102 self.writer.write(data_to_send)10398 async def _end_stream(self) -> None:99 self.h2_state.end_stream(1)104 async def end_stream(self, stream_id: int) -> None:105 self.h2_state.end_stream(stream_id)106 data_to_send = self.h2_state.data_to_send()107 self.writer.write(data_to_send)108103 async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:109 async def body_iter(110 self, stream_id: int, timeout: TimeoutConfig111 ) -> typing.AsyncIterator[bytes]:112 while True:105 event = await self._receive_event(timeout)113 event = await self.receive_event(stream_id, timeout)114 if isinstance(event, h2.events.DataReceived):115 yield event.data116 elif isinstance(event, h2.events.StreamEnded):117 del self.events[stream_id]118 break119111 async def _receive_event(self, timeout: TimeoutConfig) -> h2.events.Event:112 while not self.events:120 async def receive_event(121 self, stream_id: int, timeout: TimeoutConfig122 ) -> h2.events.Event:123 while not self.events[stream_id]:124 try:125 data = await asyncio.wait_for(126 self.reader.read(2048), timeout.read_timeout127 )128 except asyncio.TimeoutError:129 raise ReadTimeout()130131 events = self.h2_state.receive_data(data)121 self.events.extend(events)132 for event in events:133 if getattr(event, "stream_id", 0):134 self.events[event.stream_id].append(event)135136 data_to_send = self.h2_state.data_to_send()137 if data_to_send:138 self.writer.write(data_to_send)139127 return self.events.pop(0)140 return self.events[stream_id].pop(0)141129 async def _release(self) -> None:130 # if (131 # self.h11_state.our_state is h11.DONE132 # and self.h11_state.their_state is h11.DONE133 # ):134 # self.h11_state.start_next_cycle()135 # else:136 # await self.close()137142 async def release(self) -> None:143 if self.on_release is not None:144 await self.on_release(self)145146 async def close(self) -> None:142 # event = h11.ConnectionClosed()143 # try:144 # # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.145 # self.h11_state.send(event)146 # except h11.ProtocolError:147 # # If we're in some other state then it's a premature close,148 # # and we'll end up in h11.ERROR.149 # pass150151 if self.writer is not None:152 self.writer.close()147 self.writer.close()
added:httpcore/models.py+283 added
1import http2import typing3from types import TracebackType4from urllib.parse import urlsplit56from .config import SSLConfig, TimeoutConfig7from .decoders import (8 ACCEPT_ENCODING,9 SUPPORTED_DECODERS,10 Decoder,11 IdentityDecoder,12 MultiDecoder,13)14from .exceptions import ResponseClosed, StreamConsumed151617class URL:18 def __init__(self, url: str = "") -> None:19 self.components = urlsplit(url)20 if not self.components.scheme:21 raise ValueError("No scheme included in URL.")22 if self.components.scheme not in ("http", "https"):23 raise ValueError('URL scheme must be "http" or "https".')24 if not self.components.hostname:25 raise ValueError("No hostname included in URL.")2627 @property28 def scheme(self) -> str:29 return self.components.scheme3031 @property32 def netloc(self) -> str:33 return self.components.netloc3435 @property36 def path(self) -> str:37 return self.components.path3839 @property40 def query(self) -> str:41 return self.components.query4243 @property44 def hostname(self) -> str:45 return self.components.hostname4647 @property48 def port(self) -> int:49 port = self.components.port50 if port is None:51 return {"https": 443, "http": 80}[self.scheme]52 return port5354 @property55 def full_path(self) -> str:56 path = self.path or "/"57 query = self.query58 if query:59 return path + "?" + query60 return path6162 @property63 def is_secure(self) -> bool:64 return self.components.scheme == "https"6566 @property67 def origin(self) -> "Origin":68 return Origin(self)697071class Origin:72 def __init__(self, url: typing.Union[str, URL]) -> None:73 if isinstance(url, str):74 url = URL(url)75 self.is_ssl = url.scheme == "https"76 self.hostname = url.hostname.lower()77 self.port = url.port7879 def __eq__(self, other: typing.Any) -> bool:80 return (81 isinstance(other, self.__class__)82 and self.is_ssl == other.is_ssl83 and self.hostname == other.hostname84 and self.port == other.port85 )8687 def __hash__(self) -> int:88 return hash((self.is_ssl, self.hostname, self.port))899091class Request:92 def __init__(93 self,94 method: str,95 url: typing.Union[str, URL],96 *,97 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),98 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",99 ):100 self.method = method.upper()101 self.url = URL(url) if isinstance(url, str) else url102 self.headers = list(headers)103 if isinstance(body, bytes):104 self.is_streaming = False105 self.body = body106 else:107 self.is_streaming = True108 self.body_aiter = body109 self.headers = self._auto_headers() + self.headers110111 def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:112 has_host = False113 has_content_length = False114 has_accept_encoding = False115116 for header, value in self.headers:117 header = header.strip().lower()118 if header == b"host":119 has_host = True120 elif header in (b"content-length", b"transfer-encoding"):121 has_content_length = True122 elif header == b"accept-encoding":123 has_accept_encoding = True124125 headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]126127 if not has_host:128 headers.append((b"host", self.url.netloc.encode("ascii")))129 if not has_content_length:130 if self.is_streaming:131 headers.append((b"transfer-encoding", b"chunked"))132 elif self.body:133 content_length = str(len(self.body)).encode()134 headers.append((b"content-length", content_length))135 if not has_accept_encoding:136 headers.append((b"accept-encoding", ACCEPT_ENCODING))137138 return headers139140 async def stream(self) -> typing.AsyncIterator[bytes]:141 if self.is_streaming:142 async for part in self.body_aiter:143 yield part144 elif self.body:145 yield self.body146147148class Response:149 def __init__(150 self,151 status_code: int,152 *,153 reason: typing.Optional[str] = None,154 protocol: typing.Optional[str] = None,155 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),156 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",157 on_close: typing.Callable = None,158 ):159 self.status_code = status_code160 if not reason:161 try:162 self.reason = http.HTTPStatus(status_code).phrase163 except ValueError as exc:164 self.reason = ""165 else:166 self.reason = reason167 self.protocol = protocol168 self.headers = list(headers)169 self.on_close = on_close170 self.is_closed = False171 self.is_streamed = False172173 decoders = [] # type: typing.List[Decoder]174 for header, value in self.headers:175 if header.strip().lower() == b"content-encoding":176 for part in value.split(b","):177 part = part.strip().lower()178 decoder_cls = SUPPORTED_DECODERS[part]179 decoders.append(decoder_cls())180181 if len(decoders) == 0:182 self.decoder = IdentityDecoder() # type: Decoder183 elif len(decoders) == 1:184 self.decoder = decoders[0]185 else:186 self.decoder = MultiDecoder(decoders)187188 if isinstance(body, bytes):189 self.is_closed = True190 self.body = self.decoder.decode(body) + self.decoder.flush()191 else:192 self.body_aiter = body193194 async def read(self) -> bytes:195 """196 Read and return the response content.197 """198 if not hasattr(self, "body"):199 body = b""200 async for part in self.stream():201 body += part202 self.body = body203 return self.body204205 async def stream(self) -> typing.AsyncIterator[bytes]:206 """207 A byte-iterator over the decoded response content.208 This allows us to handle gzip, deflate, and brotli encoded responses.209 """210 if hasattr(self, "body"):211 yield self.body212 else:213 async for chunk in self.raw():214 yield self.decoder.decode(chunk)215 yield self.decoder.flush()216217 async def raw(self) -> typing.AsyncIterator[bytes]:218 """219 A byte-iterator over the raw response content.220 """221 if self.is_streamed:222 raise StreamConsumed()223 if self.is_closed:224 raise ResponseClosed()225 self.is_streamed = True226 async for part in self.body_aiter:227 yield part228 await self.close()229230 async def close(self) -> None:231 """232 Close the response and release the connection.233 Automatically called if the response body is read to completion.234 """235 if not self.is_closed:236 self.is_closed = True237 if self.on_close is not None:238 await self.on_close()239240241class Client:242 async def request(243 self,244 method: str,245 url: typing.Union[str, URL],246 *,247 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),248 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",249 ssl: typing.Optional[SSLConfig] = None,250 timeout: typing.Optional[TimeoutConfig] = None,251 stream: bool = False,252 ) -> Response:253 request = Request(method, url, headers=headers, body=body)254 response = await self.send(request, ssl=ssl, timeout=timeout)255 if not stream:256 try:257 await response.read()258 finally:259 await response.close()260 return response261262 async def send(263 self,264 request: Request,265 *,266 ssl: typing.Optional[SSLConfig] = None,267 timeout: typing.Optional[TimeoutConfig] = None,268 ) -> Response:269 raise NotImplementedError() # pragma: nocover270271 async def close(self) -> None:272 raise NotImplementedError() # pragma: nocover273274 async def __aenter__(self) -> "Client":275 return self276277 async def __aexit__(278 self,279 exc_type: typing.Type[BaseException] = None,280 exc_value: BaseException = None,281 traceback: TracebackType = None,282 ) -> None:283 await self.close()
modified:httpcore/sync.py+2 added-2 removed
1 unmodified line
2import typing3from types import TracebackType45from .config import SSLConfig, TimeoutConfig6from .connectionpool import ConnectionPool7from .datastructures import URL, Client, Response6from .connection_pool import ConnectionPool7from .models import URL, Client, Response8910class SyncResponse:11 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):
81 unmodified lines