Skip to content
Myr

connection.py

This file

Path

httpcore/connection.py

106 lines · 3.6 KiB · Python

Last changed by

Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae

History of this file

Take it

1import asyncio2import typing34import h2.connection5import h1167from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig8from .exceptions import ConnectTimeout9from .http2 import HTTP2Connection10from .http11 import HTTP11Connection11from .models import Client, Origin, Request, Response121314class HTTPConnection(Client):15    def __init__(16        self,17        origin: typing.Union[str, Origin],18        ssl: SSLConfig = DEFAULT_SSL_CONFIG,19        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,20        on_release: typing.Callable = None,21    ):22        self.origin = Origin(origin) if isinstance(origin, str) else origin23        self.ssl = ssl24        self.timeout = timeout25        self.on_release = on_release26        self.h11_connection = None  # type: typing.Optional[HTTP11Connection]27        self.h2_connection = None  # type: typing.Optional[HTTP2Connection]2829    async def send(30        self,31        request: Request,32        *,33        ssl: typing.Optional[SSLConfig] = None,34        timeout: typing.Optional[TimeoutConfig] = None,35    ) -> Response:36        if self.h11_connection is None and self.h2_connection is None:37            if ssl is None:38                ssl = self.ssl39            if timeout is None:40                timeout = self.timeout4142            reader, writer, protocol = await self.connect(ssl, timeout)43            if protocol == "h2":44                self.h2_connection = HTTP2Connection(45                    reader,46                    writer,47                    origin=self.origin,48                    timeout=self.timeout,49                    on_release=self.on_release,50                )51            else:52                self.h11_connection = HTTP11Connection(53                    reader,54                    writer,55                    origin=self.origin,56                    timeout=self.timeout,57                    on_release=self.on_release,58                )5960        if self.h2_connection is not None:61            response = await self.h2_connection.send(request, ssl=ssl, timeout=timeout)62        else:63            assert self.h11_connection is not None64            response = await self.h11_connection.send(request, ssl=ssl, timeout=timeout)6566        return response6768    async def close(self) -> None:69        if self.h2_connection is not None:70            await self.h2_connection.close()71        else:72            assert self.h11_connection is not None73            await self.h11_connection.close()7475    @property76    def is_closed(self) -> bool:77        if self.h2_connection is not None:78            return self.h2_connection.is_closed79        else:80            assert self.h11_connection is not None81            return self.h11_connection.is_closed8283    async def connect(84        self, ssl: SSLConfig, timeout: TimeoutConfig85    ) -> typing.Tuple[asyncio.StreamReader, asyncio.StreamWriter, str]:86        hostname = self.origin.hostname87        port = self.origin.port88        ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None8990        try:91            reader, writer = await asyncio.wait_for(  # type: ignore92                asyncio.open_connection(hostname, port, ssl=ssl_context),93                timeout.connect_timeout,94            )95        except asyncio.TimeoutError:96            raise ConnectTimeout()9798        ssl_object = writer.get_extra_info("ssl_object")99        if ssl_object is None:100            protocol = "http/1.1"101        else:102            protocol = ssl_object.selected_alpn_protocol()103        if protocol is None:104            protocol = ssl_object.selected_npn_protocol()105106        return (reader, writer, protocol)