Skip to content
Myr

default.py

This file

Path

httpcore/backends/default.py

148 lines · 4.5 KiB · Python

Last changed by

Add QueryParams classTom Christiebefore adoption211bef1

History of this file

Take it

Reorganise structureTom Christiebefore adoption0c6f618

lines 1–22why, one step back
1"""
2The `Reader` and `Writer` classes here provide a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.67These classes help encapsulate the timeout logic, make it easier to unit-test8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""11import asyncio12import ssl13import typing1415from ..config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig16from ..constants import Protocol17from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout18from ..interfaces import BasePoolSemaphore, BaseReader, BaseWriter1920OptionalTimeout = typing.Optional[TimeoutConfig]2122

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

lines 23–31why, one step back
23# Monky-patch for https://bugs.python.org/issue36709
24#25# This prevents console errors when outstanding HTTPS connections26# still exist at the point of exiting.27#28# Clients which have been opened using a `with` block, or which have29# had `close()` closed, will not exhibit this issue in the first place.3031

Add QueryParams classTom Christiebefore adoption211bef1

lines 32–35why, one step back
32_write = asyncio.selector_events._SelectorSocketTransport.write # type: ignore
333435def _fixed_write(self, data: bytes) -> None: # type: ignore

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

line 36why, one step back
36 if not self._loop.is_closed():

Add QueryParams classTom Christiebefore adoption211bef1

line 37why, one step back
37 _write(self, data)

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

lines 38–39why, one step back
38
39

Add QueryParams classTom Christiebefore adoption211bef1

line 40why, one step back
40asyncio.selector_events._SelectorSocketTransport.write = _fixed_write # type: ignore

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

line 41why, one step back
41

Add QueryParams classTom Christiebefore adoption211bef1

line 42why, one step back
42

Reorganise structureTom Christiebefore adoption0c6f618

lines 43–80why, one step back
43class Reader(BaseReader):
44 def __init__(45 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig46 ) -> None:47 self.stream_reader = stream_reader48 self.timeout = timeout4950 async def read(self, n: int, timeout: OptionalTimeout = None) -> bytes:51 if timeout is None:52 timeout = self.timeout5354 try:55 data = await asyncio.wait_for(56 self.stream_reader.read(n), timeout.read_timeout57 )58 except asyncio.TimeoutError:59 raise ReadTimeout()6061 return data626364class Writer(BaseWriter):65 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):66 self.stream_writer = stream_writer67 self.timeout = timeout6869 def write_no_block(self, data: bytes) -> None:70 self.stream_writer.write(data)7172 async def write(self, data: bytes, timeout: OptionalTimeout = None) -> None:73 if not data:74 return7576 if timeout is None:77 timeout = self.timeout7879 self.stream_writer.write(data)80 try:

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

line 81why, one step back
81 await asyncio.wait_for( # type: ignore

Reorganise structureTom Christiebefore adoption0c6f618

lines 82–148why, one step back
82 self.stream_writer.drain(), timeout.write_timeout
83 )84 except asyncio.TimeoutError:85 raise WriteTimeout()8687 async def close(self) -> None:88 self.stream_writer.close()899091class PoolSemaphore(BasePoolSemaphore):92 def __init__(self, pool_limits: PoolLimits):93 self.pool_limits = pool_limits9495 @property96 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:97 if not hasattr(self, "_semaphore"):98 max_connections = self.pool_limits.hard_limit99 if max_connections is None:100 self._semaphore = None101 else:102 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)103 return self._semaphore104105 async def acquire(self) -> None:106 if self.semaphore is None:107 return108109 timeout = self.pool_limits.pool_timeout110 try:111 await asyncio.wait_for(self.semaphore.acquire(), timeout)112 except asyncio.TimeoutError:113 raise PoolTimeout()114115 def release(self) -> None:116 if self.semaphore is None:117 return118119 self.semaphore.release()120121122async def connect(123 hostname: str,124 port: int,125 ssl_context: typing.Optional[ssl.SSLContext] = None,126 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,127) -> typing.Tuple[Reader, Writer, Protocol]:128 try:129 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore130 asyncio.open_connection(hostname, port, ssl=ssl_context),131 timeout.connect_timeout,132 )133 except asyncio.TimeoutError:134 raise ConnectTimeout()135136 ssl_object = stream_writer.get_extra_info("ssl_object")137 if ssl_object is None:138 ident = "http/1.1"139 else:140 ident = ssl_object.selected_alpn_protocol()141 if ident is None:142 ident = ssl_object.selected_npn_protocol()143144 reader = Reader(stream_reader=stream_reader, timeout=timeout)145 writer = Writer(stream_writer=stream_writer, timeout=timeout)146 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11147148 return (reader, writer, protocol)