iri2uri.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. # -*- coding: utf-8 -*-
  2. """Converts an IRI to a URI."""
  3. __author__ = "Joe Gregorio (joe@bitworking.org)"
  4. __copyright__ = "Copyright 2006, Joe Gregorio"
  5. __contributors__ = []
  6. __version__ = "1.0.0"
  7. __license__ = "MIT"
  8. import urllib.parse
  9. # Convert an IRI to a URI following the rules in RFC 3987
  10. #
  11. # The characters we need to enocde and escape are defined in the spec:
  12. #
  13. # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
  14. # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
  15. # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
  16. # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
  17. # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
  18. # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
  19. # / %xD0000-DFFFD / %xE1000-EFFFD
  20. escape_range = [
  21. (0xA0, 0xD7FF),
  22. (0xE000, 0xF8FF),
  23. (0xF900, 0xFDCF),
  24. (0xFDF0, 0xFFEF),
  25. (0x10000, 0x1FFFD),
  26. (0x20000, 0x2FFFD),
  27. (0x30000, 0x3FFFD),
  28. (0x40000, 0x4FFFD),
  29. (0x50000, 0x5FFFD),
  30. (0x60000, 0x6FFFD),
  31. (0x70000, 0x7FFFD),
  32. (0x80000, 0x8FFFD),
  33. (0x90000, 0x9FFFD),
  34. (0xA0000, 0xAFFFD),
  35. (0xB0000, 0xBFFFD),
  36. (0xC0000, 0xCFFFD),
  37. (0xD0000, 0xDFFFD),
  38. (0xE1000, 0xEFFFD),
  39. (0xF0000, 0xFFFFD),
  40. (0x100000, 0x10FFFD),
  41. ]
  42. def encode(c):
  43. retval = c
  44. i = ord(c)
  45. for low, high in escape_range:
  46. if i < low:
  47. break
  48. if i >= low and i <= high:
  49. retval = "".join(["%%%2X" % o for o in c.encode("utf-8")])
  50. break
  51. return retval
  52. def iri2uri(uri):
  53. """Convert an IRI to a URI. Note that IRIs must be
  54. passed in a unicode strings. That is, do not utf-8 encode
  55. the IRI before passing it into the function."""
  56. if isinstance(uri, str):
  57. (scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri)
  58. authority = authority.encode("idna").decode("utf-8")
  59. # For each character in 'ucschar' or 'iprivate'
  60. # 1. encode as utf-8
  61. # 2. then %-encode each octet of that utf-8
  62. uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment))
  63. uri = "".join([encode(c) for c in uri])
  64. return uri
  65. if __name__ == "__main__":
  66. import unittest
  67. class Test(unittest.TestCase):
  68. def test_uris(self):
  69. """Test that URIs are invariant under the transformation."""
  70. invariant = [
  71. "ftp://ftp.is.co.za/rfc/rfc1808.txt",
  72. "http://www.ietf.org/rfc/rfc2396.txt",
  73. "ldap://[2001:db8::7]/c=GB?objectClass?one",
  74. "mailto:John.Doe@example.com",
  75. "news:comp.infosystems.www.servers.unix",
  76. "tel:+1-816-555-1212",
  77. "telnet://192.0.2.16:80/",
  78. "urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
  79. ]
  80. for uri in invariant:
  81. self.assertEqual(uri, iri2uri(uri))
  82. def test_iri(self):
  83. """Test that the right type of escaping is done for each part of the URI."""
  84. self.assertEqual(
  85. "http://xn--o3h.com/%E2%98%84",
  86. iri2uri("http://\N{COMET}.com/\N{COMET}"),
  87. )
  88. self.assertEqual(
  89. "http://bitworking.org/?fred=%E2%98%84",
  90. iri2uri("http://bitworking.org/?fred=\N{COMET}"),
  91. )
  92. self.assertEqual(
  93. "http://bitworking.org/#%E2%98%84",
  94. iri2uri("http://bitworking.org/#\N{COMET}"),
  95. )
  96. self.assertEqual("#%E2%98%84", iri2uri("#\N{COMET}"))
  97. self.assertEqual(
  98. "/fred?bar=%E2%98%9A#%E2%98%84",
  99. iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"),
  100. )
  101. self.assertEqual(
  102. "/fred?bar=%E2%98%9A#%E2%98%84",
  103. iri2uri(iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")),
  104. )
  105. self.assertNotEqual(
  106. "/fred?bar=%E2%98%9A#%E2%98%84",
  107. iri2uri(
  108. "/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode("utf-8")
  109. ),
  110. )
  111. unittest.main()