_writable_stream.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 os
  16. from pathlib import Path
  17. from typing import Dict, Union
  18. from playwright._impl._connection import ChannelOwner
  19. # COPY_BUFSIZE is taken from shutil.py in the standard library
  20. _WINDOWS = os.name == "nt"
  21. COPY_BUFSIZE = 1024 * 1024 if _WINDOWS else 64 * 1024
  22. class WritableStream(ChannelOwner):
  23. def __init__(
  24. self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
  25. ) -> None:
  26. super().__init__(parent, type, guid, initializer)
  27. async def copy(self, path: Union[str, Path]) -> None:
  28. with open(path, "rb") as f:
  29. while True:
  30. data = f.read(COPY_BUFSIZE)
  31. if not data:
  32. break
  33. await self._channel.send(
  34. "write", None, {"binary": base64.b64encode(data).decode()}
  35. )
  36. await self._channel.send("close", None)