_stream.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. from pathlib import Path
  16. from typing import Dict, Union
  17. from playwright._impl._connection import ChannelOwner
  18. class Stream(ChannelOwner):
  19. def __init__(
  20. self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
  21. ) -> None:
  22. super().__init__(parent, type, guid, initializer)
  23. async def save_as(self, path: Union[str, Path]) -> None:
  24. file = await self._loop.run_in_executor(None, lambda: open(path, "wb"))
  25. while True:
  26. binary = await self._channel.send("read", None, {"size": 1024 * 1024})
  27. if not binary:
  28. break
  29. await self._loop.run_in_executor(
  30. None, lambda: file.write(base64.b64decode(binary))
  31. )
  32. await self._loop.run_in_executor(None, lambda: file.close())
  33. async def read_all(self) -> bytes:
  34. binary = b""
  35. while True:
  36. chunk = await self._channel.send("read", None, {"size": 1024 * 1024})
  37. if not chunk:
  38. break
  39. binary += base64.b64decode(chunk)
  40. return binary