requests.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. from __future__ import annotations
  2. import json
  3. import sys
  4. from collections.abc import AsyncGenerator, Iterator, Mapping
  5. from http import cookies as http_cookies
  6. from typing import TYPE_CHECKING, Any, Generic, NoReturn, cast
  7. import anyio
  8. from starlette._utils import AwaitableOrContextManager, AwaitableOrContextManagerWrapper
  9. from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State
  10. from starlette.exceptions import HTTPException
  11. from starlette.formparsers import FormParser, MultiPartException, MultiPartParser
  12. from starlette.types import Message, Receive, Scope, Send
  13. if TYPE_CHECKING:
  14. from python_multipart.multipart import parse_options_header
  15. from starlette.applications import Starlette
  16. from starlette.middleware.sessions import Session
  17. from starlette.routing import Router
  18. else:
  19. try:
  20. try:
  21. from python_multipart.multipart import parse_options_header
  22. except ModuleNotFoundError: # pragma: no cover
  23. from multipart.multipart import parse_options_header
  24. except ModuleNotFoundError: # pragma: no cover
  25. parse_options_header = None
  26. if sys.version_info >= (3, 13): # pragma: no cover
  27. from typing import TypeVar
  28. else: # pragma: no cover
  29. from typing_extensions import TypeVar
  30. SERVER_PUSH_HEADERS_TO_COPY = {
  31. "accept",
  32. "accept-encoding",
  33. "accept-language",
  34. "cache-control",
  35. "user-agent",
  36. }
  37. def cookie_parser(cookie_string: str) -> dict[str, str]:
  38. """
  39. This function parses a ``Cookie`` HTTP header into a dict of key/value pairs.
  40. It attempts to mimic browser cookie parsing behavior: browsers and web servers
  41. frequently disregard the spec (RFC 6265) when setting and reading cookies,
  42. so we attempt to suit the common scenarios here.
  43. This function has been adapted from Django 3.1.0.
  44. Note: we are explicitly _NOT_ using `SimpleCookie.load` because it is based
  45. on an outdated spec and will fail on lots of input we want to support
  46. """
  47. cookie_dict: dict[str, str] = {}
  48. for chunk in cookie_string.split(";"):
  49. if "=" in chunk:
  50. key, val = chunk.split("=", 1)
  51. else:
  52. # Assume an empty name per
  53. # https://bugzilla.mozilla.org/show_bug.cgi?id=169091
  54. key, val = "", chunk
  55. key, val = key.strip(), val.strip()
  56. if key or val:
  57. # unquote using Python's algorithm.
  58. cookie_dict[key] = http_cookies._unquote(val)
  59. return cookie_dict
  60. class ClientDisconnect(Exception):
  61. pass
  62. StateT = TypeVar("StateT", bound=Mapping[str, Any] | State, default=State)
  63. class HTTPConnection(Mapping[str, Any], Generic[StateT]):
  64. """
  65. A base class for incoming HTTP connections, that is used to provide
  66. any functionality that is common to both `Request` and `WebSocket`.
  67. """
  68. def __init__(self, scope: Scope, receive: Receive | None = None) -> None:
  69. assert scope["type"] in ("http", "websocket")
  70. self.scope = scope
  71. def __getitem__(self, key: str) -> Any:
  72. return self.scope[key]
  73. def __iter__(self) -> Iterator[str]:
  74. return iter(self.scope)
  75. def __len__(self) -> int:
  76. return len(self.scope)
  77. # Don't use the `abc.Mapping.__eq__` implementation.
  78. # Connection instances should never be considered equal
  79. # unless `self is other`.
  80. __eq__ = object.__eq__
  81. __hash__ = object.__hash__
  82. @property
  83. def app(self) -> Any:
  84. return self.scope["app"]
  85. @property
  86. def url(self) -> URL:
  87. if not hasattr(self, "_url"): # pragma: no branch
  88. self._url = URL(scope=self.scope)
  89. return self._url
  90. @property
  91. def base_url(self) -> URL:
  92. if not hasattr(self, "_base_url"):
  93. base_url_scope = dict(self.scope)
  94. # This is used by request.url_for, it might be used inside a Mount which
  95. # would have its own child scope with its own root_path, but the base URL
  96. # for url_for should still be the top level app root path.
  97. app_root_path = base_url_scope.get("app_root_path", base_url_scope.get("root_path", ""))
  98. path = app_root_path
  99. if not path.endswith("/"):
  100. path += "/"
  101. base_url_scope["path"] = path
  102. base_url_scope["query_string"] = b""
  103. base_url_scope["root_path"] = app_root_path
  104. self._base_url = URL(scope=base_url_scope)
  105. return self._base_url
  106. @property
  107. def headers(self) -> Headers:
  108. if not hasattr(self, "_headers"):
  109. self._headers = Headers(scope=self.scope)
  110. return self._headers
  111. @property
  112. def query_params(self) -> QueryParams:
  113. if not hasattr(self, "_query_params"): # pragma: no branch
  114. self._query_params = QueryParams(self.scope["query_string"])
  115. return self._query_params
  116. @property
  117. def path_params(self) -> dict[str, Any]:
  118. return self.scope.get("path_params", {})
  119. @property
  120. def cookies(self) -> dict[str, str]:
  121. if not hasattr(self, "_cookies"):
  122. cookies: dict[str, str] = {}
  123. cookie_headers = self.headers.getlist("cookie")
  124. for header in cookie_headers:
  125. cookies.update(cookie_parser(header))
  126. self._cookies = cookies
  127. return self._cookies
  128. @property
  129. def client(self) -> Address | None:
  130. # client is a 2 item tuple of (host, port), None if missing
  131. host_port = self.scope.get("client")
  132. if host_port is not None:
  133. return Address(*host_port)
  134. return None
  135. @property
  136. def session(self) -> dict[str, Any]:
  137. assert "session" in self.scope, "SessionMiddleware must be installed to access request.session"
  138. session: Session = self.scope["session"]
  139. # We keep the hasattr in case people actually use their own `SessionMiddleware` implementation.
  140. if hasattr(session, "mark_accessed"): # pragma: no branch
  141. session.mark_accessed()
  142. return session
  143. @property
  144. def auth(self) -> Any:
  145. assert "auth" in self.scope, "AuthenticationMiddleware must be installed to access request.auth"
  146. return self.scope["auth"]
  147. @property
  148. def user(self) -> Any:
  149. assert "user" in self.scope, "AuthenticationMiddleware must be installed to access request.user"
  150. return self.scope["user"]
  151. @property
  152. def state(self) -> StateT:
  153. if not hasattr(self, "_state"):
  154. # Ensure 'state' has an empty dict if it's not already populated.
  155. self.scope.setdefault("state", {})
  156. # Create a state instance with a reference to the dict in which it should
  157. # store info
  158. self._state = State(self.scope["state"])
  159. return cast(StateT, self._state)
  160. def url_for(self, name: str, /, **path_params: Any) -> URL:
  161. url_path_provider: Router | Starlette | None = self.scope.get("router") or self.scope.get("app")
  162. if url_path_provider is None:
  163. raise RuntimeError("The `url_for` method can only be used inside a Starlette application or with a router.")
  164. url_path = url_path_provider.url_path_for(name, **path_params)
  165. return url_path.make_absolute_url(base_url=self.base_url)
  166. async def empty_receive() -> NoReturn:
  167. raise RuntimeError("Receive channel has not been made available")
  168. async def empty_send(message: Message) -> NoReturn:
  169. raise RuntimeError("Send channel has not been made available")
  170. class Request(HTTPConnection[StateT]):
  171. _form: FormData | None
  172. def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send):
  173. super().__init__(scope)
  174. assert scope["type"] == "http"
  175. self._receive = receive
  176. self._send = send
  177. self._stream_consumed = False
  178. self._is_disconnected = False
  179. self._form = None
  180. @property
  181. def method(self) -> str:
  182. return cast(str, self.scope["method"])
  183. @property
  184. def receive(self) -> Receive:
  185. return self._receive
  186. async def stream(self) -> AsyncGenerator[bytes, None]:
  187. if hasattr(self, "_body"):
  188. yield self._body
  189. yield b""
  190. return
  191. if self._stream_consumed:
  192. raise RuntimeError("Stream consumed")
  193. while not self._stream_consumed:
  194. message = await self._receive()
  195. if message["type"] == "http.request":
  196. body = message.get("body", b"")
  197. if not message.get("more_body", False):
  198. self._stream_consumed = True
  199. if body:
  200. yield body
  201. elif message["type"] == "http.disconnect": # pragma: no branch
  202. self._is_disconnected = True
  203. raise ClientDisconnect()
  204. yield b""
  205. async def body(self) -> bytes:
  206. if not hasattr(self, "_body"):
  207. chunks: list[bytes] = []
  208. async for chunk in self.stream():
  209. chunks.append(chunk)
  210. self._body = b"".join(chunks)
  211. return self._body
  212. async def json(self) -> Any:
  213. if not hasattr(self, "_json"): # pragma: no branch
  214. body = await self.body()
  215. self._json = json.loads(body)
  216. return self._json
  217. async def _get_form(
  218. self,
  219. *,
  220. max_files: int | float = 1000,
  221. max_fields: int | float = 1000,
  222. max_part_size: int = 1024 * 1024,
  223. ) -> FormData:
  224. if self._form is None: # pragma: no branch
  225. assert parse_options_header is not None, (
  226. "The `python-multipart` library must be installed to use form parsing."
  227. )
  228. content_type_header = self.headers.get("Content-Type")
  229. content_type: bytes
  230. content_type, _ = parse_options_header(content_type_header)
  231. if content_type == b"multipart/form-data":
  232. try:
  233. multipart_parser = MultiPartParser(
  234. self.headers,
  235. self.stream(),
  236. max_files=max_files,
  237. max_fields=max_fields,
  238. max_part_size=max_part_size,
  239. )
  240. self._form = await multipart_parser.parse()
  241. except MultiPartException as exc:
  242. if "app" in self.scope:
  243. raise HTTPException(status_code=400, detail=exc.message)
  244. raise exc
  245. elif content_type == b"application/x-www-form-urlencoded":
  246. form_parser = FormParser(self.headers, self.stream())
  247. self._form = await form_parser.parse()
  248. else:
  249. self._form = FormData()
  250. return self._form
  251. def form(
  252. self,
  253. *,
  254. max_files: int | float = 1000,
  255. max_fields: int | float = 1000,
  256. max_part_size: int = 1024 * 1024,
  257. ) -> AwaitableOrContextManager[FormData]:
  258. return AwaitableOrContextManagerWrapper(
  259. self._get_form(max_files=max_files, max_fields=max_fields, max_part_size=max_part_size)
  260. )
  261. async def close(self) -> None:
  262. if self._form is not None: # pragma: no branch
  263. await self._form.close()
  264. async def is_disconnected(self) -> bool:
  265. if not self._is_disconnected:
  266. message: Message = {}
  267. # If message isn't immediately available, move on
  268. with anyio.CancelScope() as cs:
  269. cs.cancel()
  270. message = await self._receive()
  271. if message.get("type") == "http.disconnect":
  272. self._is_disconnected = True
  273. return self._is_disconnected
  274. async def send_push_promise(self, path: str) -> None:
  275. if "http.response.push" in self.scope.get("extensions", {}):
  276. raw_headers: list[tuple[bytes, bytes]] = []
  277. for name in SERVER_PUSH_HEADERS_TO_COPY:
  278. for value in self.headers.getlist(name):
  279. raw_headers.append((name.encode("latin-1"), value.encode("latin-1")))
  280. await self._send({"type": "http.response.push", "path": path, "headers": raw_headers})