base.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import typing
  2. from types import TracebackType
  3. from .._models import Request, Response
  4. T = typing.TypeVar("T", bound="BaseTransport")
  5. A = typing.TypeVar("A", bound="AsyncBaseTransport")
  6. class BaseTransport:
  7. def __enter__(self: T) -> T:
  8. return self
  9. def __exit__(
  10. self,
  11. exc_type: typing.Optional[typing.Type[BaseException]] = None,
  12. exc_value: typing.Optional[BaseException] = None,
  13. traceback: typing.Optional[TracebackType] = None,
  14. ) -> None:
  15. self.close()
  16. def handle_request(self, request: Request) -> Response:
  17. """
  18. Send a single HTTP request and return a response.
  19. Developers shouldn't typically ever need to call into this API directly,
  20. since the Client class provides all the higher level user-facing API
  21. niceties.
  22. In order to properly release any network resources, the response
  23. stream should *either* be consumed immediately, with a call to
  24. `response.stream.read()`, or else the `handle_request` call should
  25. be followed with a try/finally block to ensuring the stream is
  26. always closed.
  27. Example usage:
  28. with httpx.HTTPTransport() as transport:
  29. req = httpx.Request(
  30. method=b"GET",
  31. url=(b"https", b"www.example.com", 443, b"/"),
  32. headers=[(b"Host", b"www.example.com")],
  33. )
  34. resp = transport.handle_request(req)
  35. body = resp.stream.read()
  36. print(resp.status_code, resp.headers, body)
  37. Takes a `Request` instance as the only argument.
  38. Returns a `Response` instance.
  39. """
  40. raise NotImplementedError(
  41. "The 'handle_request' method must be implemented."
  42. ) # pragma: no cover
  43. def close(self) -> None:
  44. pass
  45. class AsyncBaseTransport:
  46. async def __aenter__(self: A) -> A:
  47. return self
  48. async def __aexit__(
  49. self,
  50. exc_type: typing.Optional[typing.Type[BaseException]] = None,
  51. exc_value: typing.Optional[BaseException] = None,
  52. traceback: typing.Optional[TracebackType] = None,
  53. ) -> None:
  54. await self.aclose()
  55. async def handle_async_request(
  56. self,
  57. request: Request,
  58. ) -> Response:
  59. raise NotImplementedError(
  60. "The 'handle_async_request' method must be implemented."
  61. ) # pragma: no cover
  62. async def aclose(self) -> None:
  63. pass