Skip to content
Myr

Merge pull request #58 from encode/sync-by-default

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

Sync by default

authored by Tom Christie · committed by GitHub · parents 21ac95a, 2a3a97a · Browse files · 15 files+614 added−615 removed
This commit

State

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

Diff stats

15 files+614 added−615 removed

  • tests:+139 added−139 removed
  • other:+475 added−476 removed

15 files+614 added−615 removed

deleted:httpcore/backends/__init__.py-2 removed
1"""2"""
deleted:httpcore/backends/default.py-148 removed
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]212223# Monky-patch for https://bugs.python.org/issue3670924#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.303132_write = asyncio.selector_events._SelectorSocketTransport.write # type: ignore333435def _fixed_write(self, data: bytes) -> None: # type: ignore36 if not self._loop.is_closed():37 _write(self, data)383940asyncio.selector_events._SelectorSocketTransport.write = _fixed_write # type: ignore414243class 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:81 await asyncio.wait_for( # type: ignore82 self.stream_writer.drain(), timeout.write_timeout83 )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)
deleted:httpcore/backends/sync.py-315 removed
1import asyncio2import typing3from types import TracebackType45from ..client import Client6from ..config import (7 DEFAULT_MAX_REDIRECTS,8 DEFAULT_POOL_LIMITS,9 DEFAULT_SSL_CONFIG,10 DEFAULT_TIMEOUT_CONFIG,11 PoolLimits,12 SSLConfig,13 TimeoutConfig,14)15from ..models import (16 URL,17 Headers,18 HeaderTypes,19 QueryParamTypes,20 Request,21 RequestData,22 Response,23 URLTypes,24)252627class SyncResponse:28 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):29 self._response = response30 self._loop = loop3132 @property33 def status_code(self) -> int:34 return self._response.status_code3536 @property37 def reason_phrase(self) -> str:38 return self._response.reason_phrase3940 @property41 def protocol(self) -> typing.Optional[str]:42 return self._response.protocol4344 @property45 def headers(self) -> Headers:46 return self._response.headers4748 @property49 def content(self) -> bytes:50 return self._response.content5152 @property53 def text(self) -> str:54 return self._response.text5556 def read(self) -> bytes:57 return self._loop.run_until_complete(self._response.read())5859 def stream(self) -> typing.Iterator[bytes]:60 inner = self._response.stream()61 while True:62 try:63 yield self._loop.run_until_complete(inner.__anext__())64 except StopAsyncIteration as exc:65 break6667 def raw(self) -> typing.Iterator[bytes]:68 inner = self._response.raw()69 while True:70 try:71 yield self._loop.run_until_complete(inner.__anext__())72 except StopAsyncIteration as exc:73 break7475 def close(self) -> None:76 return self._loop.run_until_complete(self._response.close())7778 def __repr__(self) -> str:79 class_name = self.__class__.__name__80 return f"<{class_name}(status_code={self.status_code})>"818283class SyncClient:84 def __init__(85 self,86 ssl: SSLConfig = DEFAULT_SSL_CONFIG,87 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,88 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,89 max_redirects: int = DEFAULT_MAX_REDIRECTS,90 ) -> None:91 self._client = Client(92 ssl=ssl,93 timeout=timeout,94 pool_limits=pool_limits,95 max_redirects=max_redirects,96 )97 self._loop = asyncio.new_event_loop()9899 def request(100 self,101 method: str,102 url: URLTypes,103 *,104 data: RequestData = b"",105 query_params: QueryParamTypes = None,106 headers: HeaderTypes = None,107 stream: bool = False,108 allow_redirects: bool = True,109 ssl: SSLConfig = None,110 timeout: TimeoutConfig = None,111 ) -> SyncResponse:112 request = Request(113 method, url, data=data, query_params=query_params, headers=headers114 )115 self.prepare_request(request)116 response = self.send(117 request,118 stream=stream,119 allow_redirects=allow_redirects,120 ssl=ssl,121 timeout=timeout,122 )123 return response124125 def get(126 self,127 url: URLTypes,128 *,129 query_params: QueryParamTypes = None,130 headers: HeaderTypes = None,131 stream: bool = False,132 allow_redirects: bool = True,133 ssl: SSLConfig = None,134 timeout: TimeoutConfig = None,135 ) -> SyncResponse:136 return self.request(137 "GET",138 url,139 headers=headers,140 stream=stream,141 allow_redirects=allow_redirects,142 ssl=ssl,143 timeout=timeout,144 )145146 def options(147 self,148 url: URLTypes,149 *,150 query_params: QueryParamTypes = None,151 headers: HeaderTypes = None,152 stream: bool = False,153 allow_redirects: bool = True,154 ssl: SSLConfig = None,155 timeout: TimeoutConfig = None,156 ) -> SyncResponse:157 return self.request(158 "OPTIONS",159 url,160 headers=headers,161 stream=stream,162 allow_redirects=allow_redirects,163 ssl=ssl,164 timeout=timeout,165 )166167 def head(168 self,169 url: URLTypes,170 *,171 query_params: QueryParamTypes = None,172 headers: HeaderTypes = None,173 stream: bool = False,174 allow_redirects: bool = False, #  Note: Differs to usual default.175 ssl: SSLConfig = None,176 timeout: TimeoutConfig = None,177 ) -> SyncResponse:178 return self.request(179 "HEAD",180 url,181 headers=headers,182 stream=stream,183 allow_redirects=allow_redirects,184 ssl=ssl,185 timeout=timeout,186 )187188 def post(189 self,190 url: URLTypes,191 *,192 data: RequestData = b"",193 query_params: QueryParamTypes = None,194 headers: HeaderTypes = None,195 stream: bool = False,196 allow_redirects: bool = True,197 ssl: SSLConfig = None,198 timeout: TimeoutConfig = None,199 ) -> SyncResponse:200 return self.request(201 "POST",202 url,203 data=data,204 headers=headers,205 stream=stream,206 allow_redirects=allow_redirects,207 ssl=ssl,208 timeout=timeout,209 )210211 def put(212 self,213 url: URLTypes,214 *,215 data: RequestData = b"",216 query_params: QueryParamTypes = None,217 headers: HeaderTypes = None,218 stream: bool = False,219 allow_redirects: bool = True,220 ssl: SSLConfig = None,221 timeout: TimeoutConfig = None,222 ) -> SyncResponse:223 return self.request(224 "PUT",225 url,226 data=data,227 headers=headers,228 stream=stream,229 allow_redirects=allow_redirects,230 ssl=ssl,231 timeout=timeout,232 )233234 def patch(235 self,236 url: URLTypes,237 *,238 data: RequestData = b"",239 query_params: QueryParamTypes = None,240 headers: HeaderTypes = None,241 stream: bool = False,242 allow_redirects: bool = True,243 ssl: SSLConfig = None,244 timeout: TimeoutConfig = None,245 ) -> SyncResponse:246 return self.request(247 "PATCH",248 url,249 data=data,250 headers=headers,251 stream=stream,252 allow_redirects=allow_redirects,253 ssl=ssl,254 timeout=timeout,255 )256257 def delete(258 self,259 url: URLTypes,260 *,261 data: RequestData = b"",262 query_params: QueryParamTypes = None,263 headers: HeaderTypes = None,264 stream: bool = False,265 allow_redirects: bool = True,266 ssl: SSLConfig = None,267 timeout: TimeoutConfig = None,268 ) -> SyncResponse:269 return self.request(270 "DELETE",271 url,272 data=data,273 headers=headers,274 stream=stream,275 allow_redirects=allow_redirects,276 ssl=ssl,277 timeout=timeout,278 )279280 def prepare_request(self, request: Request) -> None:281 self._client.prepare_request(request)282283 def send(284 self,285 request: Request,286 *,287 stream: bool = False,288 allow_redirects: bool = True,289 ssl: SSLConfig = None,290 timeout: TimeoutConfig = None,291 ) -> SyncResponse:292 response = self._loop.run_until_complete(293 self._client.send(294 request,295 stream=stream,296 allow_redirects=allow_redirects,297 ssl=ssl,298 timeout=timeout,299 )300 )301 return SyncResponse(response, self._loop)302303 def close(self) -> None:304 self._loop.run_until_complete(self._client.close())305306 def __enter__(self) -> "SyncClient":307 return self308309 def __exit__(310 self,311 exc_type: typing.Type[BaseException] = None,312 exc_value: BaseException = None,313 traceback: TracebackType = None,314 ) -> None:315 self.close()
modified:httpcore/dispatch/connection_pool.py+1 added-1 removed
1import collections.abc2import typing34from ..backends.default import PoolSemaphore4from ..concurrency import PoolSemaphore5from ..config import (6 DEFAULT_CA_BUNDLE_PATH,7 DEFAULT_POOL_LIMITS,8 DEFAULT_SSL_CONFIG,
155 unmodified lines
modified:httpcore/dispatch/connection.py+1 added-1 removed
2 unmodified lines
34import h2.connection5import h1167from ..backends.default import connect7from ..concurrency import connect8from ..config import (9 DEFAULT_SSL_CONFIG,10 DEFAULT_TIMEOUT_CONFIG,11 SSLConfig,
92 unmodified lines
modified:httpcore/__init__.py+1 added-2 removed
1from .backends.sync import SyncClient2from .client import Client1from .client import AsyncClient, Client2from .config import PoolLimits, SSLConfig, TimeoutConfig3from .constants import Protocol, codes4from .dispatch.connection import HTTPConnection5from .dispatch.connection_pool import ConnectionPool
21 unmodified lines
modified:httpcore/client.py+241 added-2 removed
1import asyncio2import typing3from types import TracebackType45from .config import (
16 unmodified lines
22 QueryParamTypes,23 Request,24 RequestData,25 Response,26 SyncResponse,27 URLTypes,28)293029class Client:31class AsyncClient:32 def __init__(33 self,34 ssl: SSLConfig = DEFAULT_SSL_CONFIG,35 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,
320 unmodified lines
356357 async def close(self) -> None:358 await self.dispatch.close()359358 async def __aenter__(self) -> "Client":360 async def __aenter__(self) -> "AsyncClient":361 return self362363 async def __aexit__(364 self,
1 unmodified line
366 exc_value: BaseException = None,367 traceback: TracebackType = None,368 ) -> None:369 await self.close()370371372class Client:373 def __init__(374 self,375 ssl: SSLConfig = DEFAULT_SSL_CONFIG,376 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,377 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,378 max_redirects: int = DEFAULT_MAX_REDIRECTS,379 dispatch: Dispatcher = None,380 ) -> None:381 self._client = AsyncClient(382 ssl=ssl,383 timeout=timeout,384 pool_limits=pool_limits,385 max_redirects=max_redirects,386 dispatch=dispatch,387 )388 self._loop = asyncio.new_event_loop()389390 def request(391 self,392 method: str,393 url: URLTypes,394 *,395 data: RequestData = b"",396 query_params: QueryParamTypes = None,397 headers: HeaderTypes = None,398 stream: bool = False,399 allow_redirects: bool = True,400 ssl: SSLConfig = None,401 timeout: TimeoutConfig = None,402 ) -> SyncResponse:403 request = Request(404 method, url, data=data, query_params=query_params, headers=headers405 )406 self.prepare_request(request)407 response = self.send(408 request,409 stream=stream,410 allow_redirects=allow_redirects,411 ssl=ssl,412 timeout=timeout,413 )414 return response415416 def get(417 self,418 url: URLTypes,419 *,420 query_params: QueryParamTypes = None,421 headers: HeaderTypes = None,422 stream: bool = False,423 allow_redirects: bool = True,424 ssl: SSLConfig = None,425 timeout: TimeoutConfig = None,426 ) -> SyncResponse:427 return self.request(428 "GET",429 url,430 headers=headers,431 stream=stream,432 allow_redirects=allow_redirects,433 ssl=ssl,434 timeout=timeout,435 )436437 def options(438 self,439 url: URLTypes,440 *,441 query_params: QueryParamTypes = None,442 headers: HeaderTypes = None,443 stream: bool = False,444 allow_redirects: bool = True,445 ssl: SSLConfig = None,446 timeout: TimeoutConfig = None,447 ) -> SyncResponse:448 return self.request(449 "OPTIONS",450 url,451 headers=headers,452 stream=stream,453 allow_redirects=allow_redirects,454 ssl=ssl,455 timeout=timeout,456 )457458 def head(459 self,460 url: URLTypes,461 *,462 query_params: QueryParamTypes = None,463 headers: HeaderTypes = None,464 stream: bool = False,465 allow_redirects: bool = False, #  Note: Differs to usual default.466 ssl: SSLConfig = None,467 timeout: TimeoutConfig = None,468 ) -> SyncResponse:469 return self.request(470 "HEAD",471 url,472 headers=headers,473 stream=stream,474 allow_redirects=allow_redirects,475 ssl=ssl,476 timeout=timeout,477 )478479 def post(480 self,481 url: URLTypes,482 *,483 data: RequestData = b"",484 query_params: QueryParamTypes = None,485 headers: HeaderTypes = None,486 stream: bool = False,487 allow_redirects: bool = True,488 ssl: SSLConfig = None,489 timeout: TimeoutConfig = None,490 ) -> SyncResponse:491 return self.request(492 "POST",493 url,494 data=data,495 headers=headers,496 stream=stream,497 allow_redirects=allow_redirects,498 ssl=ssl,499 timeout=timeout,500 )501502 def put(503 self,504 url: URLTypes,505 *,506 data: RequestData = b"",507 query_params: QueryParamTypes = None,508 headers: HeaderTypes = None,509 stream: bool = False,510 allow_redirects: bool = True,511 ssl: SSLConfig = None,512 timeout: TimeoutConfig = None,513 ) -> SyncResponse:514 return self.request(515 "PUT",516 url,517 data=data,518 headers=headers,519 stream=stream,520 allow_redirects=allow_redirects,521 ssl=ssl,522 timeout=timeout,523 )524525 def patch(526 self,527 url: URLTypes,528 *,529 data: RequestData = b"",530 query_params: QueryParamTypes = None,531 headers: HeaderTypes = None,532 stream: bool = False,533 allow_redirects: bool = True,534 ssl: SSLConfig = None,535 timeout: TimeoutConfig = None,536 ) -> SyncResponse:537 return self.request(538 "PATCH",539 url,540 data=data,541 headers=headers,542 stream=stream,543 allow_redirects=allow_redirects,544 ssl=ssl,545 timeout=timeout,546 )547548 def delete(549 self,550 url: URLTypes,551 *,552 data: RequestData = b"",553 query_params: QueryParamTypes = None,554 headers: HeaderTypes = None,555 stream: bool = False,556 allow_redirects: bool = True,557 ssl: SSLConfig = None,558 timeout: TimeoutConfig = None,559 ) -> SyncResponse:560 return self.request(561 "DELETE",562 url,563 data=data,564 headers=headers,565 stream=stream,566 allow_redirects=allow_redirects,567 ssl=ssl,568 timeout=timeout,569 )570571 def prepare_request(self, request: Request) -> None:572 self._client.prepare_request(request)573574 def send(575 self,576 request: Request,577 *,578 stream: bool = False,579 allow_redirects: bool = True,580 ssl: SSLConfig = None,581 timeout: TimeoutConfig = None,582 ) -> SyncResponse:583 response = self._loop.run_until_complete(584 self._client.send(585 request,586 stream=stream,587 allow_redirects=allow_redirects,588 ssl=ssl,589 timeout=timeout,590 )591 )592 return SyncResponse(response, self._loop)593594 def close(self) -> None:595 self._loop.run_until_complete(self._client.close())596597 def __enter__(self) -> "Client":598 return self599600 def __exit__(601 self,602 exc_type: typing.Type[BaseException] = None,603 exc_value: BaseException = None,604 traceback: TracebackType = None,605 ) -> None:606 self.close()
added:httpcore/concurrency.py+148 added
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]212223# Monky-patch for https://bugs.python.org/issue3670924#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.303132_write = asyncio.selector_events._SelectorSocketTransport.write # type: ignore333435def _fixed_write(self, data: bytes) -> None: # type: ignore36 if not self._loop.is_closed():37 _write(self, data)383940asyncio.selector_events._SelectorSocketTransport.write = _fixed_write # type: ignore414243class 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:81 await asyncio.wait_for( # type: ignore82 self.stream_writer.drain(), timeout.write_timeout83 )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)
modified:httpcore/models.py+81 added-4 removed
1import asyncio2import cgi3import typing4from urllib.parse import parse_qsl, urlencode5
717 unmodified lines
723 )724 and "location" in self.headers725 )726726 def __repr__(self) -> str:727 class_name = self.__class__.__name__728 return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"729727 def raise_for_status(self) -> None:728 """729 Raise the `HttpError` if one occurred.730 """
10 unmodified lines
741 message = ""742743 if message:744 raise HttpError(message)745746 def __repr__(self) -> str:747 class_name = self.__class__.__name__748 return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"749750751class SyncResponse:752 """753 A thread-synchronous response. This class proxies onto a `Response`754 instance, providing standard synchronous interfaces where required.755 """756757 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):758 self._response = response759 self._loop = loop760761 @property762 def status_code(self) -> int:763 return self._response.status_code764765 @property766 def reason_phrase(self) -> str:767 return self._response.reason_phrase768769 @property770 def protocol(self) -> typing.Optional[str]:771 return self._response.protocol772773 @property774 def url(self) -> typing.Optional[URL]:775 return self._response.url776777 @property778 def request(self) -> typing.Optional[Request]:779 return self._response.request780781 @property782 def headers(self) -> Headers:783 return self._response.headers784785 @property786 def content(self) -> bytes:787 return self._response.content788789 @property790 def text(self) -> str:791 return self._response.text792793 @property794 def encoding(self) -> str:795 return self._response.encoding796797 @property798 def is_redirect(self) -> bool:799 return self._response.is_redirect800801 def raise_for_status(self) -> None:802 return self._response.raise_for_status()803804 def read(self) -> bytes:805 return self._loop.run_until_complete(self._response.read())806807 def stream(self) -> typing.Iterator[bytes]:808 inner = self._response.stream()809 while True:810 try:811 yield self._loop.run_until_complete(inner.__anext__())812 except StopAsyncIteration as exc:813 break814815 def raw(self) -> typing.Iterator[bytes]:816 inner = self._response.raw()817 while True:818 try:819 yield self._loop.run_until_complete(inner.__anext__())820 except StopAsyncIteration as exc:821 break822823 def close(self) -> None:824 return self._loop.run_until_complete(self._response.close())
added:tests/client/test_asnyc_client.py+67 added
1import pytest23import httpcore456@pytest.mark.asyncio7async def test_get(server):8 url = "http://127.0.0.1:8000/"9 async with httpcore.AsyncClient() as client:10 response = await client.get(url)11 assert response.status_code == 20012 assert response.text == "Hello, world!"131415@pytest.mark.asyncio16async def test_post(server):17 url = "http://127.0.0.1:8000/"18 async with httpcore.AsyncClient() as client:19 response = await client.post(url, data=b"Hello, world!")20 assert response.status_code == 200212223@pytest.mark.asyncio24async def test_stream_response(server):25 async with httpcore.AsyncClient() as client:26 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)27 assert response.status_code == 20028 body = await response.read()29 assert body == b"Hello, world!"30 assert response.content == b"Hello, world!"313233@pytest.mark.asyncio34async def test_access_content_stream_response(server):35 async with httpcore.AsyncClient() as client:36 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)37 assert response.status_code == 20038 with pytest.raises(httpcore.ResponseNotRead):39 response.content404142@pytest.mark.asyncio43async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"4748 async with httpcore.AsyncClient() as client:49 response = await client.request(50 "POST", "http://127.0.0.1:8000/", data=hello_world()51 )52 assert response.status_code == 200535455@pytest.mark.asyncio56async def test_raise_for_status(server):57 async with httpcore.AsyncClient() as client:58 for status_code in (200, 400, 404, 500, 505):59 response = await client.request(60 "GET", f"http://127.0.0.1:8000/status/{status_code}"61 )6263 if 400 <= status_code < 600:64 with pytest.raises(httpcore.exceptions.HttpError):65 response.raise_for_status()66 else:67 assert response.raise_for_status() is None
modified:tests/client/test_client.py+51 added-47 removed
1import asyncio2import functools34import pytest56import httpcore786@pytest.mark.asyncio7async def test_get(server):8 url = "http://127.0.0.1:8000/"9 async with httpcore.Client() as client:10 response = await client.get(url)11 assert response.status_code == 20012 assert response.text == "Hello, world!"9def threadpool(func):10 """11 Our sync tests should run in seperate thread to the uvicorn server.12 """1314 @functools.wraps(func)15 async def wrapped(*args, **kwargs):16 nonlocal func1715@pytest.mark.asyncio16async def test_post(server):17 url = "http://127.0.0.1:8000/"18 async with httpcore.Client() as client:19 response = await client.post(url, data=b"Hello, world!")20 assert response.status_code == 20018 loop = asyncio.get_event_loop()19 if kwargs:20 func = functools.partial(func, **kwargs)21 await loop.run_in_executor(None, func, *args)2223 return pytest.mark.asyncio(wrapped)2423@pytest.mark.asyncio24async def test_stream_response(server):25 async with httpcore.Client() as client:26 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)2526@threadpool27def test_get(server):28 with httpcore.Client() as http:29 response = http.get("http://127.0.0.1:8000/")30 assert response.status_code == 20028 body = await response.read()29 assert body == b"Hello, world!"31 assert response.content == b"Hello, world!"32 assert response.text == "Hello, world!"333433@pytest.mark.asyncio34async def test_access_content_stream_response(server):35 async with httpcore.Client() as client:36 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)35@threadpool36def test_post(server):37 with httpcore.Client() as http:38 response = http.post("http://127.0.0.1:8000/", data=b"Hello, world!")39 assert response.status_code == 20038 with pytest.raises(httpcore.ResponseNotRead):39 response.content40 assert response.reason_phrase == "OK"414242@pytest.mark.asyncio43async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"4748 async with httpcore.Client() as client:49 response = await client.request(50 "POST", "http://127.0.0.1:8000/", data=hello_world()51 )43@threadpool44def test_stream_response(server):45 with httpcore.Client() as http:46 response = http.get("http://127.0.0.1:8000/", stream=True)47 assert response.status_code == 20048 content = response.read()49 assert content == b"Hello, world!"505155@pytest.mark.asyncio56async def test_raise_for_status(server):57 async with httpcore.Client() as client:58 for status_code in (200, 400, 404, 500, 505):59 response = await client.request(60 "GET", f"http://127.0.0.1:8000/status/{status_code}"61 )52@threadpool53def test_stream_iterator(server):54 with httpcore.Client() as http:55 response = http.get("http://127.0.0.1:8000/", stream=True)56 assert response.status_code == 20057 body = b""58 for chunk in response.stream():59 body += chunk60 assert body == b"Hello, world!"6163 if 400 <= status_code < 600:64 with pytest.raises(httpcore.exceptions.HttpError):65 response.raise_for_status()66 else:67 assert response.raise_for_status() is None6263@threadpool64def test_raw_iterator(server):65 with httpcore.Client() as http:66 response = http.get("http://127.0.0.1:8000/", stream=True)67 assert response.status_code == 20068 body = b""69 for chunk in response.raw():70 body += chunk71 assert body == b"Hello, world!"
modified:tests/client/test_redirects.py+17 added-17 removed
3 unmodified lines
4import pytest56from httpcore import (7 URL,8 Client,8 AsyncClient,9 Dispatcher,10 RedirectBodyUnavailable,11 RedirectLoop,12 Request,
74 unmodified lines
878889@pytest.mark.asyncio90async def test_redirect_301():91 client = Client(dispatch=MockDispatch())91 client = AsyncClient(dispatch=MockDispatch())92 response = await client.request("POST", "https://example.org/redirect_301")93 assert response.status_code == codes.ok94 assert response.url == URL("https://example.org/")95 assert len(response.history) == 1969798@pytest.mark.asyncio99async def test_redirect_302():100 client = Client(dispatch=MockDispatch())100 client = AsyncClient(dispatch=MockDispatch())101 response = await client.request("POST", "https://example.org/redirect_302")102 assert response.status_code == codes.ok103 assert response.url == URL("https://example.org/")104 assert len(response.history) == 1105106107@pytest.mark.asyncio108async def test_redirect_303():109 client = Client(dispatch=MockDispatch())109 client = AsyncClient(dispatch=MockDispatch())110 response = await client.request("GET", "https://example.org/redirect_303")111 assert response.status_code == codes.ok112 assert response.url == URL("https://example.org/")113 assert len(response.history) == 1114115116@pytest.mark.asyncio117async def test_disallow_redirects():118 client = Client(dispatch=MockDispatch())118 client = AsyncClient(dispatch=MockDispatch())119 response = await client.request(120 "POST", "https://example.org/redirect_303", allow_redirects=False121 )122 assert response.status_code == codes.see_other
7 unmodified lines
130131132@pytest.mark.asyncio133async def test_relative_redirect():134 client = Client(dispatch=MockDispatch())134 client = AsyncClient(dispatch=MockDispatch())135 response = await client.request("GET", "https://example.org/relative_redirect")136 assert response.status_code == codes.ok137 assert response.url == URL("https://example.org/")138 assert len(response.history) == 1139140141@pytest.mark.asyncio142async def test_no_scheme_redirect():143 client = Client(dispatch=MockDispatch())143 client = AsyncClient(dispatch=MockDispatch())144 response = await client.request("GET", "https://example.org/no_scheme_redirect")145 assert response.status_code == codes.ok146 assert response.url == URL("https://example.org/")147 assert len(response.history) == 1148149150@pytest.mark.asyncio151async def test_fragment_redirect():152 client = Client(dispatch=MockDispatch())152 client = AsyncClient(dispatch=MockDispatch())153 url = "https://example.org/relative_redirect#fragment"154 response = await client.request("GET", url)155 assert response.status_code == codes.ok156 assert response.url == URL("https://example.org/#fragment")
1 unmodified line
158159160@pytest.mark.asyncio161async def test_multiple_redirects():162 client = Client(dispatch=MockDispatch())162 client = AsyncClient(dispatch=MockDispatch())163 url = "https://example.org/multiple_redirects?count=20"164 response = await client.request("GET", url)165 assert response.status_code == codes.ok166 assert response.url == URL("https://example.org/multiple_redirects")
1 unmodified line
168169170@pytest.mark.asyncio171async def test_too_many_redirects():172 client = Client(dispatch=MockDispatch())172 client = AsyncClient(dispatch=MockDispatch())173 with pytest.raises(TooManyRedirects):174 await client.request("GET", "https://example.org/multiple_redirects?count=21")175176177@pytest.mark.asyncio178async def test_too_many_redirects_calling_next():179 client = Client(dispatch=MockDispatch())179 client = AsyncClient(dispatch=MockDispatch())180 url = "https://example.org/multiple_redirects?count=21"181 response = await client.request("GET", url, allow_redirects=False)182 with pytest.raises(TooManyRedirects):183 while response.is_redirect:
1 unmodified line
185186187@pytest.mark.asyncio188async def test_redirect_loop():189 client = Client(dispatch=MockDispatch())189 client = AsyncClient(dispatch=MockDispatch())190 with pytest.raises(RedirectLoop):191 await client.request("GET", "https://example.org/redirect_loop")192193194@pytest.mark.asyncio195async def test_redirect_loop_calling_next():196 client = Client(dispatch=MockDispatch())196 client = AsyncClient(dispatch=MockDispatch())197 url = "https://example.org/redirect_loop"198 response = await client.request("GET", url, allow_redirects=False)199 with pytest.raises(RedirectLoop):200 while response.is_redirect:
1 unmodified line
202203204@pytest.mark.asyncio205async def test_cross_domain_redirect():206 client = Client(dispatch=MockDispatch())206 client = AsyncClient(dispatch=MockDispatch())207 url = "https://example.com/cross_domain"208 headers = {"Authorization": "abc"}209 response = await client.request("GET", url, headers=headers)210 data = json.loads(response.content.decode())
2 unmodified lines
213214215@pytest.mark.asyncio216async def test_same_domain_redirect():217 client = Client(dispatch=MockDispatch())217 client = AsyncClient(dispatch=MockDispatch())218 url = "https://example.org/cross_domain"219 headers = {"Authorization": "abc"}220 response = await client.request("GET", url, headers=headers)221 data = json.loads(response.content.decode())
2 unmodified lines
224225226@pytest.mark.asyncio227async def test_body_redirect():228 client = Client(dispatch=MockDispatch())228 client = AsyncClient(dispatch=MockDispatch())229 url = "https://example.org/redirect_body"230 data = b"Example request body"231 response = await client.request("POST", url, data=data)232 data = json.loads(response.content.decode())
2 unmodified lines
235236237@pytest.mark.asyncio238async def test_cannot_redirect_streaming_body():239 client = Client(dispatch=MockDispatch())239 client = AsyncClient(dispatch=MockDispatch())240 url = "https://example.org/redirect_body"241242 async def streaming_body():243 yield b"Example request body"
3 unmodified lines
deleted:tests/test_sync.py-71 removed
1import asyncio2import functools34import pytest56import httpcore789def threadpool(func):10 """11 Our sync tests should run in seperate thread to the uvicorn server.12 """1314 @functools.wraps(func)15 async def wrapped(*args, **kwargs):16 nonlocal func1718 loop = asyncio.get_event_loop()19 if kwargs:20 func = functools.partial(func, **kwargs)21 await loop.run_in_executor(None, func, *args)2223 return pytest.mark.asyncio(wrapped)242526@threadpool27def test_get(server):28 with httpcore.SyncClient() as http:29 response = http.get("http://127.0.0.1:8000/")30 assert response.status_code == 20031 assert response.content == b"Hello, world!"32 assert response.text == "Hello, world!"333435@threadpool36def test_post(server):37 with httpcore.SyncClient() as http:38 response = http.post("http://127.0.0.1:8000/", data=b"Hello, world!")39 assert response.status_code == 20040 assert response.reason_phrase == "OK"414243@threadpool44def test_stream_response(server):45 with httpcore.SyncClient() as http:46 response = http.get("http://127.0.0.1:8000/", stream=True)47 assert response.status_code == 20048 content = response.read()49 assert content == b"Hello, world!"505152@threadpool53def test_stream_iterator(server):54 with httpcore.SyncClient() as http:55 response = http.get("http://127.0.0.1:8000/", stream=True)56 assert response.status_code == 20057 body = b""58 for chunk in response.stream():59 body += chunk60 assert body == b"Hello, world!"616263@threadpool64def test_raw_iterator(server):65 with httpcore.SyncClient() as http:66 response = http.get("http://127.0.0.1:8000/", stream=True)67 assert response.status_code == 20068 body = b""69 for chunk in response.raw():70 body += chunk71 assert body == b"Hello, world!"
modified:tests/test_timeouts.py+4 added-4 removed
1import pytest23from httpcore import (4 Client,4 AsyncClient,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,8 ReadTimeout,
4 unmodified lines
13@pytest.mark.asyncio14async def test_read_timeout(server):15 timeout = TimeoutConfig(read_timeout=0.0001)1617 async with Client(timeout=timeout) as client:17 async with AsyncClient(timeout=timeout) as client:18 with pytest.raises(ReadTimeout):19 await client.get("http://127.0.0.1:8000/slow_response")202122@pytest.mark.asyncio23async def test_connect_timeout(server):24 timeout = TimeoutConfig(connect_timeout=0.0001)2526 async with Client(timeout=timeout) as client:26 async with AsyncClient(timeout=timeout) as client:27 with pytest.raises(ConnectTimeout):28 # See https://stackoverflow.com/questions/100841/29 await client.get("http://10.255.255.1/")30
1 unmodified line
32@pytest.mark.asyncio33async def test_pool_timeout(server):34 pool_limits = PoolLimits(hard_limit=1, pool_timeout=0.0001)3536 async with Client(pool_limits=pool_limits) as client:36 async with AsyncClient(pool_limits=pool_limits) as client:37 response = await client.get("http://127.0.0.1:8000/", stream=True)3839 with pytest.raises(PoolTimeout):40 await client.get("http://localhost:8000/")
2 unmodified lines
modified:README.md+2 added-1 removed
11 unmodified lines
1213## Feature support1415* `HTTP/1.1` and `HTTP/2` Support.16* `async`/`await` support for non-thread-blocking HTTP requests.16* `async`/`await` support for non-blocking HTTP requests.17* Strict timeouts everywhere by default.18* Fully type annotated.19* 100% test coverage. *TODO - Almost there.*2021Plus all the standard features of requests...
214 unmodified lines