_models.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. from __future__ import annotations
  2. import base64
  3. import ssl
  4. import typing
  5. import urllib.parse
  6. # Functions for typechecking...
  7. ByteOrStr = typing.Union[bytes, str]
  8. HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]]
  9. HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr]
  10. HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None]
  11. Extensions = typing.MutableMapping[str, typing.Any]
  12. def enforce_bytes(value: bytes | str, *, name: str) -> bytes:
  13. """
  14. Any arguments that are ultimately represented as bytes can be specified
  15. either as bytes or as strings.
  16. However we enforce that any string arguments must only contain characters in
  17. the plain ASCII range. chr(0)...chr(127). If you need to use characters
  18. outside that range then be precise, and use a byte-wise argument.
  19. """
  20. if isinstance(value, str):
  21. try:
  22. return value.encode("ascii")
  23. except UnicodeEncodeError:
  24. raise TypeError(f"{name} strings may not include unicode characters.")
  25. elif isinstance(value, bytes):
  26. return value
  27. seen_type = type(value).__name__
  28. raise TypeError(f"{name} must be bytes or str, but got {seen_type}.")
  29. def enforce_url(value: URL | bytes | str, *, name: str) -> URL:
  30. """
  31. Type check for URL parameters.
  32. """
  33. if isinstance(value, (bytes, str)):
  34. return URL(value)
  35. elif isinstance(value, URL):
  36. return value
  37. seen_type = type(value).__name__
  38. raise TypeError(f"{name} must be a URL, bytes, or str, but got {seen_type}.")
  39. def enforce_headers(
  40. value: HeadersAsMapping | HeadersAsSequence | None = None, *, name: str
  41. ) -> list[tuple[bytes, bytes]]:
  42. """
  43. Convienence function that ensure all items in request or response headers
  44. are either bytes or strings in the plain ASCII range.
  45. """
  46. if value is None:
  47. return []
  48. elif isinstance(value, typing.Mapping):
  49. return [
  50. (
  51. enforce_bytes(k, name="header name"),
  52. enforce_bytes(v, name="header value"),
  53. )
  54. for k, v in value.items()
  55. ]
  56. elif isinstance(value, typing.Sequence):
  57. return [
  58. (
  59. enforce_bytes(k, name="header name"),
  60. enforce_bytes(v, name="header value"),
  61. )
  62. for k, v in value
  63. ]
  64. seen_type = type(value).__name__
  65. raise TypeError(
  66. f"{name} must be a mapping or sequence of two-tuples, but got {seen_type}."
  67. )
  68. def enforce_stream(
  69. value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None,
  70. *,
  71. name: str,
  72. ) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]:
  73. if value is None:
  74. return ByteStream(b"")
  75. elif isinstance(value, bytes):
  76. return ByteStream(value)
  77. return value
  78. # * https://tools.ietf.org/html/rfc3986#section-3.2.3
  79. # * https://url.spec.whatwg.org/#url-miscellaneous
  80. # * https://url.spec.whatwg.org/#scheme-state
  81. DEFAULT_PORTS = {
  82. b"ftp": 21,
  83. b"http": 80,
  84. b"https": 443,
  85. b"ws": 80,
  86. b"wss": 443,
  87. }
  88. def include_request_headers(
  89. headers: list[tuple[bytes, bytes]],
  90. *,
  91. url: "URL",
  92. content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes],
  93. ) -> list[tuple[bytes, bytes]]:
  94. headers_set = set(k.lower() for k, v in headers)
  95. if b"host" not in headers_set:
  96. default_port = DEFAULT_PORTS.get(url.scheme)
  97. if url.port is None or url.port == default_port:
  98. header_value = url.host
  99. else:
  100. header_value = b"%b:%d" % (url.host, url.port)
  101. headers = [(b"Host", header_value)] + headers
  102. if (
  103. content is not None
  104. and b"content-length" not in headers_set
  105. and b"transfer-encoding" not in headers_set
  106. ):
  107. if isinstance(content, bytes):
  108. content_length = str(len(content)).encode("ascii")
  109. headers += [(b"Content-Length", content_length)]
  110. else:
  111. headers += [(b"Transfer-Encoding", b"chunked")] # pragma: nocover
  112. return headers
  113. # Interfaces for byte streams...
  114. class ByteStream:
  115. """
  116. A container for non-streaming content, and that supports both sync and async
  117. stream iteration.
  118. """
  119. def __init__(self, content: bytes) -> None:
  120. self._content = content
  121. def __iter__(self) -> typing.Iterator[bytes]:
  122. yield self._content
  123. async def __aiter__(self) -> typing.AsyncIterator[bytes]:
  124. yield self._content
  125. def __repr__(self) -> str:
  126. return f"<{self.__class__.__name__} [{len(self._content)} bytes]>"
  127. class Origin:
  128. def __init__(self, scheme: bytes, host: bytes, port: int) -> None:
  129. self.scheme = scheme
  130. self.host = host
  131. self.port = port
  132. def __eq__(self, other: typing.Any) -> bool:
  133. return (
  134. isinstance(other, Origin)
  135. and self.scheme == other.scheme
  136. and self.host == other.host
  137. and self.port == other.port
  138. )
  139. def __str__(self) -> str:
  140. scheme = self.scheme.decode("ascii")
  141. host = self.host.decode("ascii")
  142. port = str(self.port)
  143. return f"{scheme}://{host}:{port}"
  144. class URL:
  145. """
  146. Represents the URL against which an HTTP request may be made.
  147. The URL may either be specified as a plain string, for convienence:
  148. ```python
  149. url = httpcore.URL("https://www.example.com/")
  150. ```
  151. Or be constructed with explicitily pre-parsed components:
  152. ```python
  153. url = httpcore.URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/')
  154. ```
  155. Using this second more explicit style allows integrations that are using
  156. `httpcore` to pass through URLs that have already been parsed in order to use
  157. libraries such as `rfc-3986` rather than relying on the stdlib. It also ensures
  158. that URL parsing is treated identically at both the networking level and at any
  159. higher layers of abstraction.
  160. The four components are important here, as they allow the URL to be precisely
  161. specified in a pre-parsed format. They also allow certain types of request to
  162. be created that could not otherwise be expressed.
  163. For example, an HTTP request to `http://www.example.com/` forwarded via a proxy
  164. at `http://localhost:8080`...
  165. ```python
  166. # Constructs an HTTP request with a complete URL as the target:
  167. # GET https://www.example.com/ HTTP/1.1
  168. url = httpcore.URL(
  169. scheme=b'http',
  170. host=b'localhost',
  171. port=8080,
  172. target=b'https://www.example.com/'
  173. )
  174. request = httpcore.Request(
  175. method="GET",
  176. url=url
  177. )
  178. ```
  179. Another example is constructing an `OPTIONS *` request...
  180. ```python
  181. # Constructs an 'OPTIONS *' HTTP request:
  182. # OPTIONS * HTTP/1.1
  183. url = httpcore.URL(scheme=b'https', host=b'www.example.com', target=b'*')
  184. request = httpcore.Request(method="OPTIONS", url=url)
  185. ```
  186. This kind of request is not possible to formulate with a URL string,
  187. because the `/` delimiter is always used to demark the target from the
  188. host/port portion of the URL.
  189. For convenience, string-like arguments may be specified either as strings or
  190. as bytes. However, once a request is being issue over-the-wire, the URL
  191. components are always ultimately required to be a bytewise representation.
  192. In order to avoid any ambiguity over character encodings, when strings are used
  193. as arguments, they must be strictly limited to the ASCII range `chr(0)`-`chr(127)`.
  194. If you require a bytewise representation that is outside this range you must
  195. handle the character encoding directly, and pass a bytes instance.
  196. """
  197. def __init__(
  198. self,
  199. url: bytes | str = "",
  200. *,
  201. scheme: bytes | str = b"",
  202. host: bytes | str = b"",
  203. port: int | None = None,
  204. target: bytes | str = b"",
  205. ) -> None:
  206. """
  207. Parameters:
  208. url: The complete URL as a string or bytes.
  209. scheme: The URL scheme as a string or bytes.
  210. Typically either `"http"` or `"https"`.
  211. host: The URL host as a string or bytes. Such as `"www.example.com"`.
  212. port: The port to connect to. Either an integer or `None`.
  213. target: The target of the HTTP request. Such as `"/items?search=red"`.
  214. """
  215. if url:
  216. parsed = urllib.parse.urlparse(enforce_bytes(url, name="url"))
  217. self.scheme = parsed.scheme
  218. self.host = parsed.hostname or b""
  219. self.port = parsed.port
  220. self.target = (parsed.path or b"/") + (
  221. b"?" + parsed.query if parsed.query else b""
  222. )
  223. else:
  224. self.scheme = enforce_bytes(scheme, name="scheme")
  225. self.host = enforce_bytes(host, name="host")
  226. self.port = port
  227. self.target = enforce_bytes(target, name="target")
  228. @property
  229. def origin(self) -> Origin:
  230. default_port = {
  231. b"http": 80,
  232. b"https": 443,
  233. b"ws": 80,
  234. b"wss": 443,
  235. b"socks5": 1080,
  236. b"socks5h": 1080,
  237. }[self.scheme]
  238. return Origin(
  239. scheme=self.scheme, host=self.host, port=self.port or default_port
  240. )
  241. def __eq__(self, other: typing.Any) -> bool:
  242. return (
  243. isinstance(other, URL)
  244. and other.scheme == self.scheme
  245. and other.host == self.host
  246. and other.port == self.port
  247. and other.target == self.target
  248. )
  249. def __bytes__(self) -> bytes:
  250. if self.port is None:
  251. return b"%b://%b%b" % (self.scheme, self.host, self.target)
  252. return b"%b://%b:%d%b" % (self.scheme, self.host, self.port, self.target)
  253. def __repr__(self) -> str:
  254. return (
  255. f"{self.__class__.__name__}(scheme={self.scheme!r}, "
  256. f"host={self.host!r}, port={self.port!r}, target={self.target!r})"
  257. )
  258. class Request:
  259. """
  260. An HTTP request.
  261. """
  262. def __init__(
  263. self,
  264. method: bytes | str,
  265. url: URL | bytes | str,
  266. *,
  267. headers: HeaderTypes = None,
  268. content: bytes
  269. | typing.Iterable[bytes]
  270. | typing.AsyncIterable[bytes]
  271. | None = None,
  272. extensions: Extensions | None = None,
  273. ) -> None:
  274. """
  275. Parameters:
  276. method: The HTTP request method, either as a string or bytes.
  277. For example: `GET`.
  278. url: The request URL, either as a `URL` instance, or as a string or bytes.
  279. For example: `"https://www.example.com".`
  280. headers: The HTTP request headers.
  281. content: The content of the request body.
  282. extensions: A dictionary of optional extra information included on
  283. the request. Possible keys include `"timeout"`, and `"trace"`.
  284. """
  285. self.method: bytes = enforce_bytes(method, name="method")
  286. self.url: URL = enforce_url(url, name="url")
  287. self.headers: list[tuple[bytes, bytes]] = enforce_headers(
  288. headers, name="headers"
  289. )
  290. self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = (
  291. enforce_stream(content, name="content")
  292. )
  293. self.extensions = {} if extensions is None else extensions
  294. if "target" in self.extensions:
  295. self.url = URL(
  296. scheme=self.url.scheme,
  297. host=self.url.host,
  298. port=self.url.port,
  299. target=self.extensions["target"],
  300. )
  301. def __repr__(self) -> str:
  302. return f"<{self.__class__.__name__} [{self.method!r}]>"
  303. class Response:
  304. """
  305. An HTTP response.
  306. """
  307. def __init__(
  308. self,
  309. status: int,
  310. *,
  311. headers: HeaderTypes = None,
  312. content: bytes
  313. | typing.Iterable[bytes]
  314. | typing.AsyncIterable[bytes]
  315. | None = None,
  316. extensions: Extensions | None = None,
  317. ) -> None:
  318. """
  319. Parameters:
  320. status: The HTTP status code of the response. For example `200`.
  321. headers: The HTTP response headers.
  322. content: The content of the response body.
  323. extensions: A dictionary of optional extra information included on
  324. the responseself.Possible keys include `"http_version"`,
  325. `"reason_phrase"`, and `"network_stream"`.
  326. """
  327. self.status: int = status
  328. self.headers: list[tuple[bytes, bytes]] = enforce_headers(
  329. headers, name="headers"
  330. )
  331. self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = (
  332. enforce_stream(content, name="content")
  333. )
  334. self.extensions = {} if extensions is None else extensions
  335. self._stream_consumed = False
  336. @property
  337. def content(self) -> bytes:
  338. if not hasattr(self, "_content"):
  339. if isinstance(self.stream, typing.Iterable):
  340. raise RuntimeError(
  341. "Attempted to access 'response.content' on a streaming response. "
  342. "Call 'response.read()' first."
  343. )
  344. else:
  345. raise RuntimeError(
  346. "Attempted to access 'response.content' on a streaming response. "
  347. "Call 'await response.aread()' first."
  348. )
  349. return self._content
  350. def __repr__(self) -> str:
  351. return f"<{self.__class__.__name__} [{self.status}]>"
  352. # Sync interface...
  353. def read(self) -> bytes:
  354. if not isinstance(self.stream, typing.Iterable): # pragma: nocover
  355. raise RuntimeError(
  356. "Attempted to read an asynchronous response using 'response.read()'. "
  357. "You should use 'await response.aread()' instead."
  358. )
  359. if not hasattr(self, "_content"):
  360. self._content = b"".join([part for part in self.iter_stream()])
  361. return self._content
  362. def iter_stream(self) -> typing.Iterator[bytes]:
  363. if not isinstance(self.stream, typing.Iterable): # pragma: nocover
  364. raise RuntimeError(
  365. "Attempted to stream an asynchronous response using 'for ... in "
  366. "response.iter_stream()'. "
  367. "You should use 'async for ... in response.aiter_stream()' instead."
  368. )
  369. if self._stream_consumed:
  370. raise RuntimeError(
  371. "Attempted to call 'for ... in response.iter_stream()' more than once."
  372. )
  373. self._stream_consumed = True
  374. for chunk in self.stream:
  375. yield chunk
  376. def close(self) -> None:
  377. if not isinstance(self.stream, typing.Iterable): # pragma: nocover
  378. raise RuntimeError(
  379. "Attempted to close an asynchronous response using 'response.close()'. "
  380. "You should use 'await response.aclose()' instead."
  381. )
  382. if hasattr(self.stream, "close"):
  383. self.stream.close()
  384. # Async interface...
  385. async def aread(self) -> bytes:
  386. if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover
  387. raise RuntimeError(
  388. "Attempted to read an synchronous response using "
  389. "'await response.aread()'. "
  390. "You should use 'response.read()' instead."
  391. )
  392. if not hasattr(self, "_content"):
  393. self._content = b"".join([part async for part in self.aiter_stream()])
  394. return self._content
  395. async def aiter_stream(self) -> typing.AsyncIterator[bytes]:
  396. if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover
  397. raise RuntimeError(
  398. "Attempted to stream an synchronous response using 'async for ... in "
  399. "response.aiter_stream()'. "
  400. "You should use 'for ... in response.iter_stream()' instead."
  401. )
  402. if self._stream_consumed:
  403. raise RuntimeError(
  404. "Attempted to call 'async for ... in response.aiter_stream()' "
  405. "more than once."
  406. )
  407. self._stream_consumed = True
  408. async for chunk in self.stream:
  409. yield chunk
  410. async def aclose(self) -> None:
  411. if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover
  412. raise RuntimeError(
  413. "Attempted to close a synchronous response using "
  414. "'await response.aclose()'. "
  415. "You should use 'response.close()' instead."
  416. )
  417. if hasattr(self.stream, "aclose"):
  418. await self.stream.aclose()
  419. class Proxy:
  420. def __init__(
  421. self,
  422. url: URL | bytes | str,
  423. auth: tuple[bytes | str, bytes | str] | None = None,
  424. headers: HeadersAsMapping | HeadersAsSequence | None = None,
  425. ssl_context: ssl.SSLContext | None = None,
  426. ):
  427. self.url = enforce_url(url, name="url")
  428. self.headers = enforce_headers(headers, name="headers")
  429. self.ssl_context = ssl_context
  430. if auth is not None:
  431. username = enforce_bytes(auth[0], name="auth")
  432. password = enforce_bytes(auth[1], name="auth")
  433. userpass = username + b":" + password
  434. authorization = b"Basic " + base64.b64encode(userpass)
  435. self.auth: tuple[bytes, bytes] | None = (username, password)
  436. self.headers = [(b"Proxy-Authorization", authorization)] + self.headers
  437. else:
  438. self.auth = None