_idna.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- test-case-name: twisted.test.test_sslverify -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Shared interface to IDNA encoding and decoding, using the C{idna} PyPI package
  6. if available, otherwise the stdlib implementation.
  7. """
  8. def _idnaBytes(text: str) -> bytes:
  9. """
  10. Convert some text typed by a human into some ASCII bytes.
  11. This is provided to allow us to use the U{partially-broken IDNA
  12. implementation in the standard library <http://bugs.python.org/issue17305>}
  13. if the more-correct U{idna <https://pypi.python.org/pypi/idna>} package is
  14. not available; C{service_identity} is somewhat stricter about this.
  15. @param text: A domain name, hopefully.
  16. @type text: L{unicode}
  17. @return: The domain name's IDNA representation, encoded as bytes.
  18. @rtype: L{bytes}
  19. """
  20. try:
  21. import idna
  22. except ImportError:
  23. return text.encode("idna")
  24. else:
  25. return idna.encode(text)
  26. def _idnaText(octets: bytes) -> str:
  27. """
  28. Convert some IDNA-encoded octets into some human-readable text.
  29. Currently only used by the tests.
  30. @param octets: Some bytes representing a hostname.
  31. @type octets: L{bytes}
  32. @return: A human-readable domain name.
  33. @rtype: L{unicode}
  34. """
  35. try:
  36. import idna
  37. except ImportError:
  38. return octets.decode("idna")
  39. else:
  40. return idna.decode(octets)