_fetch.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. # Copyright (c) Microsoft Corporation.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import base64
  15. import json
  16. import mimetypes
  17. import pathlib
  18. import typing
  19. from pathlib import Path
  20. from typing import Any, Dict, List, Optional, Union, cast
  21. import playwright._impl._network as network
  22. from playwright._impl._api_structures import (
  23. ClientCertificate,
  24. FilePayload,
  25. FormField,
  26. Headers,
  27. HttpCredentials,
  28. ProxySettings,
  29. ServerFilePayload,
  30. StorageState,
  31. )
  32. from playwright._impl._connection import ChannelOwner, from_channel
  33. from playwright._impl._errors import is_target_closed_error
  34. from playwright._impl._form_data import FormData
  35. from playwright._impl._helper import (
  36. Error,
  37. NameValue,
  38. TargetClosedError,
  39. TimeoutSettings,
  40. async_readfile,
  41. async_writefile,
  42. is_file_payload,
  43. locals_to_params,
  44. object_to_array,
  45. to_impl,
  46. )
  47. from playwright._impl._network import serialize_headers, to_client_certificates_protocol
  48. from playwright._impl._tracing import Tracing
  49. if typing.TYPE_CHECKING:
  50. from playwright._impl._playwright import Playwright
  51. FormType = Union[Dict[str, Union[bool, float, str]], FormData]
  52. DataType = Union[Any, bytes, str]
  53. MultipartType = Union[Dict[str, Union[bytes, bool, float, str, FilePayload]], FormData]
  54. ParamsType = Union[Dict[str, Union[bool, float, str]], str]
  55. class APIRequest:
  56. def __init__(self, playwright: "Playwright") -> None:
  57. self.playwright = playwright
  58. self._loop = playwright._loop
  59. self._dispatcher_fiber = playwright._connection._dispatcher_fiber
  60. async def new_context(
  61. self,
  62. baseURL: str = None,
  63. extraHTTPHeaders: Dict[str, str] = None,
  64. httpCredentials: HttpCredentials = None,
  65. ignoreHTTPSErrors: bool = None,
  66. proxy: ProxySettings = None,
  67. userAgent: str = None,
  68. timeout: float = None,
  69. storageState: Union[StorageState, str, Path] = None,
  70. clientCertificates: List[ClientCertificate] = None,
  71. failOnStatusCode: bool = None,
  72. maxRedirects: int = None,
  73. ) -> "APIRequestContext":
  74. params = locals_to_params(locals())
  75. if "storageState" in params:
  76. storage_state = params["storageState"]
  77. if not isinstance(storage_state, dict) and storage_state:
  78. params["storageState"] = json.loads(
  79. (await async_readfile(storage_state)).decode()
  80. )
  81. if "extraHTTPHeaders" in params:
  82. params["extraHTTPHeaders"] = serialize_headers(params["extraHTTPHeaders"])
  83. params["clientCertificates"] = await to_client_certificates_protocol(
  84. params.get("clientCertificates")
  85. )
  86. context = cast(
  87. APIRequestContext,
  88. from_channel(
  89. await self.playwright._channel.send("newRequest", None, params)
  90. ),
  91. )
  92. context._timeout_settings.set_default_timeout(timeout)
  93. return context
  94. class APIRequestContext(ChannelOwner):
  95. def __init__(
  96. self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
  97. ) -> None:
  98. super().__init__(parent, type, guid, initializer)
  99. self._tracing: Tracing = from_channel(initializer["tracing"])
  100. self._close_reason: Optional[str] = None
  101. self._timeout_settings = TimeoutSettings(None)
  102. async def dispose(self, reason: str = None) -> None:
  103. self._close_reason = reason
  104. await self._tracing._export_all_hars()
  105. try:
  106. await self._channel.send("dispose", None, {"reason": reason})
  107. except Error as e:
  108. if is_target_closed_error(e):
  109. return
  110. raise e
  111. self._tracing._reset_stack_counter()
  112. @property
  113. def tracing(self) -> Tracing:
  114. return self._tracing
  115. async def delete(
  116. self,
  117. url: str,
  118. params: ParamsType = None,
  119. headers: Headers = None,
  120. data: DataType = None,
  121. form: FormType = None,
  122. multipart: MultipartType = None,
  123. timeout: float = None,
  124. failOnStatusCode: bool = None,
  125. ignoreHTTPSErrors: bool = None,
  126. maxRedirects: int = None,
  127. maxRetries: int = None,
  128. ) -> "APIResponse":
  129. return await self.fetch(
  130. url,
  131. method="DELETE",
  132. params=params,
  133. headers=headers,
  134. data=data,
  135. form=form,
  136. multipart=multipart,
  137. timeout=timeout,
  138. failOnStatusCode=failOnStatusCode,
  139. ignoreHTTPSErrors=ignoreHTTPSErrors,
  140. maxRedirects=maxRedirects,
  141. maxRetries=maxRetries,
  142. )
  143. async def head(
  144. self,
  145. url: str,
  146. params: ParamsType = None,
  147. headers: Headers = None,
  148. data: DataType = None,
  149. form: FormType = None,
  150. multipart: MultipartType = None,
  151. timeout: float = None,
  152. failOnStatusCode: bool = None,
  153. ignoreHTTPSErrors: bool = None,
  154. maxRedirects: int = None,
  155. maxRetries: int = None,
  156. ) -> "APIResponse":
  157. return await self.fetch(
  158. url,
  159. method="HEAD",
  160. params=params,
  161. headers=headers,
  162. data=data,
  163. form=form,
  164. multipart=multipart,
  165. timeout=timeout,
  166. failOnStatusCode=failOnStatusCode,
  167. ignoreHTTPSErrors=ignoreHTTPSErrors,
  168. maxRedirects=maxRedirects,
  169. maxRetries=maxRetries,
  170. )
  171. async def get(
  172. self,
  173. url: str,
  174. params: ParamsType = None,
  175. headers: Headers = None,
  176. data: DataType = None,
  177. form: FormType = None,
  178. multipart: MultipartType = None,
  179. timeout: float = None,
  180. failOnStatusCode: bool = None,
  181. ignoreHTTPSErrors: bool = None,
  182. maxRedirects: int = None,
  183. maxRetries: int = None,
  184. ) -> "APIResponse":
  185. return await self.fetch(
  186. url,
  187. method="GET",
  188. params=params,
  189. headers=headers,
  190. data=data,
  191. form=form,
  192. multipart=multipart,
  193. timeout=timeout,
  194. failOnStatusCode=failOnStatusCode,
  195. ignoreHTTPSErrors=ignoreHTTPSErrors,
  196. maxRedirects=maxRedirects,
  197. maxRetries=maxRetries,
  198. )
  199. async def patch(
  200. self,
  201. url: str,
  202. params: ParamsType = None,
  203. headers: Headers = None,
  204. data: DataType = None,
  205. form: FormType = None,
  206. multipart: MultipartType = None,
  207. timeout: float = None,
  208. failOnStatusCode: bool = None,
  209. ignoreHTTPSErrors: bool = None,
  210. maxRedirects: int = None,
  211. maxRetries: int = None,
  212. ) -> "APIResponse":
  213. return await self.fetch(
  214. url,
  215. method="PATCH",
  216. params=params,
  217. headers=headers,
  218. data=data,
  219. form=form,
  220. multipart=multipart,
  221. timeout=timeout,
  222. failOnStatusCode=failOnStatusCode,
  223. ignoreHTTPSErrors=ignoreHTTPSErrors,
  224. maxRedirects=maxRedirects,
  225. maxRetries=maxRetries,
  226. )
  227. async def put(
  228. self,
  229. url: str,
  230. params: ParamsType = None,
  231. headers: Headers = None,
  232. data: DataType = None,
  233. form: FormType = None,
  234. multipart: MultipartType = None,
  235. timeout: float = None,
  236. failOnStatusCode: bool = None,
  237. ignoreHTTPSErrors: bool = None,
  238. maxRedirects: int = None,
  239. maxRetries: int = None,
  240. ) -> "APIResponse":
  241. return await self.fetch(
  242. url,
  243. method="PUT",
  244. params=params,
  245. headers=headers,
  246. data=data,
  247. form=form,
  248. multipart=multipart,
  249. timeout=timeout,
  250. failOnStatusCode=failOnStatusCode,
  251. ignoreHTTPSErrors=ignoreHTTPSErrors,
  252. maxRedirects=maxRedirects,
  253. maxRetries=maxRetries,
  254. )
  255. async def post(
  256. self,
  257. url: str,
  258. params: ParamsType = None,
  259. headers: Headers = None,
  260. data: DataType = None,
  261. form: FormType = None,
  262. multipart: MultipartType = None,
  263. timeout: float = None,
  264. failOnStatusCode: bool = None,
  265. ignoreHTTPSErrors: bool = None,
  266. maxRedirects: int = None,
  267. maxRetries: int = None,
  268. ) -> "APIResponse":
  269. return await self.fetch(
  270. url,
  271. method="POST",
  272. params=params,
  273. headers=headers,
  274. data=data,
  275. form=form,
  276. multipart=multipart,
  277. timeout=timeout,
  278. failOnStatusCode=failOnStatusCode,
  279. ignoreHTTPSErrors=ignoreHTTPSErrors,
  280. maxRedirects=maxRedirects,
  281. maxRetries=maxRetries,
  282. )
  283. async def fetch(
  284. self,
  285. urlOrRequest: Union[str, network.Request],
  286. params: ParamsType = None,
  287. method: str = None,
  288. headers: Headers = None,
  289. data: DataType = None,
  290. form: FormType = None,
  291. multipart: MultipartType = None,
  292. timeout: float = None,
  293. failOnStatusCode: bool = None,
  294. ignoreHTTPSErrors: bool = None,
  295. maxRedirects: int = None,
  296. maxRetries: int = None,
  297. ) -> "APIResponse":
  298. url = urlOrRequest if isinstance(urlOrRequest, str) else None
  299. request = (
  300. cast(network.Request, to_impl(urlOrRequest))
  301. if isinstance(to_impl(urlOrRequest), network.Request)
  302. else None
  303. )
  304. assert request or isinstance(
  305. urlOrRequest, str
  306. ), "First argument must be either URL string or Request"
  307. return await self._inner_fetch(
  308. request,
  309. url,
  310. method,
  311. headers,
  312. data,
  313. params,
  314. form,
  315. multipart,
  316. timeout,
  317. failOnStatusCode,
  318. ignoreHTTPSErrors,
  319. maxRedirects,
  320. maxRetries,
  321. )
  322. async def _inner_fetch(
  323. self,
  324. request: Optional[network.Request],
  325. url: Optional[str],
  326. method: str = None,
  327. headers: Headers = None,
  328. data: DataType = None,
  329. params: ParamsType = None,
  330. form: FormType = None,
  331. multipart: MultipartType = None,
  332. timeout: float = None,
  333. failOnStatusCode: bool = None,
  334. ignoreHTTPSErrors: bool = None,
  335. maxRedirects: int = None,
  336. maxRetries: int = None,
  337. ) -> "APIResponse":
  338. if self._close_reason:
  339. raise TargetClosedError(self._close_reason)
  340. assert (
  341. (1 if data else 0) + (1 if form else 0) + (1 if multipart else 0)
  342. ) <= 1, "Only one of 'data', 'form' or 'multipart' can be specified"
  343. assert (
  344. maxRedirects is None or maxRedirects >= 0
  345. ), "'max_redirects' must be greater than or equal to '0'"
  346. assert (
  347. maxRetries is None or maxRetries >= 0
  348. ), "'max_retries' must be greater than or equal to '0'"
  349. url = url or (request.url if request else url)
  350. method = method or (request.method if request else "GET")
  351. # Cannot call allHeaders() here as the request may be paused inside route handler.
  352. headers_obj = headers or (request.headers if request else None)
  353. serialized_headers = serialize_headers(headers_obj) if headers_obj else None
  354. json_data: Any = None
  355. form_data: Optional[List[NameValue]] = None
  356. multipart_data: Optional[List[FormField]] = None
  357. post_data_buffer: Optional[bytes] = None
  358. if data is not None:
  359. if isinstance(data, str):
  360. if is_json_content_type(serialized_headers):
  361. json_data = data if is_json_parsable(data) else json.dumps(data)
  362. else:
  363. post_data_buffer = data.encode()
  364. elif isinstance(data, bytes):
  365. post_data_buffer = data
  366. elif isinstance(data, (dict, list, int, bool)):
  367. json_data = json.dumps(data)
  368. else:
  369. raise Error(f"Unsupported 'data' type: {type(data)}")
  370. elif form:
  371. if isinstance(form, FormData):
  372. form_data = []
  373. for fd_name, fd_value in form._fields:
  374. if isinstance(fd_value, (pathlib.Path, dict)):
  375. raise Error(
  376. f"Form field {fd_name!r} must be a string, number or boolean. Use 'multipart' for file uploads."
  377. )
  378. form_data.append(NameValue(name=fd_name, value=str(fd_value)))
  379. else:
  380. form_data = object_to_array(form)
  381. elif multipart:
  382. multipart_data = []
  383. if isinstance(multipart, FormData):
  384. for fd_name, fd_value in multipart._fields:
  385. multipart_data.append(
  386. await _form_data_field_to_form_field(fd_name, fd_value)
  387. )
  388. else:
  389. # Convert file-like values to ServerFilePayload structs.
  390. for name, value in multipart.items():
  391. if is_file_payload(value):
  392. payload = cast(FilePayload, value)
  393. assert isinstance(
  394. payload["buffer"], bytes
  395. ), f"Unexpected buffer type of 'data.{name}'"
  396. multipart_data.append(
  397. FormField(name=name, file=file_payload_to_json(payload))
  398. )
  399. elif isinstance(value, str):
  400. multipart_data.append(FormField(name=name, value=value))
  401. if (
  402. post_data_buffer is None
  403. and json_data is None
  404. and form_data is None
  405. and multipart_data is None
  406. ):
  407. post_data_buffer = request.post_data_buffer if request else None
  408. post_data = (
  409. base64.b64encode(post_data_buffer).decode() if post_data_buffer else None
  410. )
  411. response = await self._channel.send(
  412. "fetch",
  413. self._timeout_settings.timeout,
  414. {
  415. "url": url,
  416. "timeout": timeout,
  417. "params": object_to_array(params) if isinstance(params, dict) else None,
  418. "encodedParams": params if isinstance(params, str) else None,
  419. "method": method,
  420. "headers": serialized_headers,
  421. "postData": post_data,
  422. "jsonData": json_data,
  423. "formData": form_data,
  424. "multipartData": multipart_data,
  425. "failOnStatusCode": failOnStatusCode,
  426. "ignoreHTTPSErrors": ignoreHTTPSErrors,
  427. "maxRedirects": maxRedirects,
  428. "maxRetries": maxRetries,
  429. },
  430. )
  431. return APIResponse(self, response)
  432. async def storage_state(
  433. self,
  434. path: Union[pathlib.Path, str] = None,
  435. indexedDB: bool = None,
  436. ) -> StorageState:
  437. result = await self._channel.send_return_as_dict(
  438. "storageState", None, {"indexedDB": indexedDB}
  439. )
  440. if path:
  441. await async_writefile(path, json.dumps(result))
  442. return result
  443. def file_payload_to_json(payload: FilePayload) -> ServerFilePayload:
  444. return ServerFilePayload(
  445. name=payload["name"],
  446. mimeType=payload["mimeType"],
  447. buffer=base64.b64encode(payload["buffer"]).decode(),
  448. )
  449. async def _form_data_field_to_form_field(name: str, value: Any) -> FormField:
  450. if isinstance(value, pathlib.Path):
  451. mime_type, _ = mimetypes.guess_type(str(value))
  452. return FormField(
  453. name=name,
  454. file=ServerFilePayload(
  455. name=value.name,
  456. mimeType=mime_type or "application/octet-stream",
  457. buffer=base64.b64encode(await async_readfile(str(value))).decode(),
  458. ),
  459. )
  460. if is_file_payload(value):
  461. payload = cast(FilePayload, value)
  462. assert isinstance(
  463. payload["buffer"], bytes
  464. ), f"Unexpected buffer type of form field {name!r}"
  465. return FormField(name=name, file=file_payload_to_json(payload))
  466. if isinstance(value, (str, int, float, bool)):
  467. return FormField(name=name, value=str(value))
  468. raise Error(f"Unsupported form field {name!r} value type: {type(value).__name__}")
  469. class APIResponse:
  470. def __init__(self, context: APIRequestContext, initializer: Dict) -> None:
  471. self._loop = context._loop
  472. self._dispatcher_fiber = context._connection._dispatcher_fiber
  473. self._request = context
  474. self._initializer = initializer
  475. self._headers = network.RawHeaders(initializer["headers"])
  476. def __repr__(self) -> str:
  477. return f"<APIResponse url={self.url!r} status={self.status!r} status_text={self.status_text!r}>"
  478. @property
  479. def ok(self) -> bool:
  480. return self.status >= 200 and self.status <= 299
  481. @property
  482. def url(self) -> str:
  483. return self._initializer["url"]
  484. @property
  485. def status(self) -> int:
  486. return self._initializer["status"]
  487. @property
  488. def status_text(self) -> str:
  489. return self._initializer["statusText"]
  490. @property
  491. def headers(self) -> Headers:
  492. return self._headers.headers()
  493. @property
  494. def headers_array(self) -> network.HeadersArray:
  495. return self._headers.headers_array()
  496. async def body(self) -> bytes:
  497. try:
  498. result = await self._request._connection.wrap_api_call(
  499. lambda: self._request._channel.send_return_as_dict(
  500. "fetchResponseBody",
  501. None,
  502. {
  503. "fetchUid": self._fetch_uid,
  504. },
  505. ),
  506. True,
  507. )
  508. if result is None:
  509. raise Error("Response has been disposed")
  510. return base64.b64decode(result["binary"])
  511. except Error as exc:
  512. if is_target_closed_error(exc):
  513. raise Error("Response has been disposed")
  514. raise exc
  515. async def text(self) -> str:
  516. content = await self.body()
  517. return content.decode()
  518. async def json(self) -> Any:
  519. content = await self.text()
  520. return json.loads(content)
  521. async def dispose(self) -> None:
  522. await self._request._channel.send(
  523. "disposeAPIResponse",
  524. None,
  525. {
  526. "fetchUid": self._fetch_uid,
  527. },
  528. )
  529. @property
  530. def _fetch_uid(self) -> str:
  531. return self._initializer["fetchUid"]
  532. async def _fetch_log(self) -> List[str]:
  533. return await self._request._channel.send(
  534. "fetchLog",
  535. None,
  536. {
  537. "fetchUid": self._fetch_uid,
  538. },
  539. )
  540. def is_json_content_type(headers: network.HeadersArray = None) -> bool:
  541. if not headers:
  542. return False
  543. for header in headers:
  544. if header["name"] == "Content-Type":
  545. return header["value"].startswith("application/json")
  546. return False
  547. def is_json_parsable(value: Any) -> bool:
  548. if not isinstance(value, str):
  549. return False
  550. try:
  551. json.loads(value)
  552. return True
  553. except json.JSONDecodeError:
  554. return False