requests.py 11 KB

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