makefile.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. """
  3. backports.makefile
  4. ~~~~~~~~~~~~~~~~~~
  5. Backports the Python 3 ``socket.makefile`` method for use with anything that
  6. wants to create a "fake" socket object.
  7. """
  8. import io
  9. from socket import SocketIO
  10. def backport_makefile(
  11. self, mode="r", buffering=None, encoding=None, errors=None, newline=None
  12. ):
  13. """
  14. Backport of ``socket.makefile`` from Python 3.5.
  15. """
  16. if not set(mode) <= {"r", "w", "b"}:
  17. raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
  18. writing = "w" in mode
  19. reading = "r" in mode or not writing
  20. assert reading or writing
  21. binary = "b" in mode
  22. rawmode = ""
  23. if reading:
  24. rawmode += "r"
  25. if writing:
  26. rawmode += "w"
  27. raw = SocketIO(self, rawmode)
  28. self._makefile_refs += 1
  29. if buffering is None:
  30. buffering = -1
  31. if buffering < 0:
  32. buffering = io.DEFAULT_BUFFER_SIZE
  33. if buffering == 0:
  34. if not binary:
  35. raise ValueError("unbuffered streams must be binary")
  36. return raw
  37. if reading and writing:
  38. buffer = io.BufferedRWPair(raw, raw, buffering)
  39. elif reading:
  40. buffer = io.BufferedReader(raw, buffering)
  41. else:
  42. assert writing
  43. buffer = io.BufferedWriter(raw, buffering)
  44. if binary:
  45. return buffer
  46. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  47. text.mode = mode
  48. return text