4 Converts an IRI to a URI.
7 __author__ = "Joe Gregorio (joe@bitworking.org)"
8 __copyright__ = "Copyright 2006, Joe Gregorio"
18 # Convert an IRI to a URI following the rules in RFC 3987
20 # The characters we need to enocde and escape are defined in the spec:
22 # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
23 # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
24 # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
25 # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
26 # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
27 # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
28 # / %xD0000-DFFFD / %xE1000-EFFFD
56 for low, high in escape_range:
59 if i >= low and i <= high:
60 retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')])
66 """Convert an IRI to a URI. Note that IRIs must be
67 passed in a unicode strings. That is, do not utf-8 encode
68 the IRI before passing it into the function."""
69 if isinstance(uri ,unicode):
70 (scheme, authority, path, query, fragment) = urlparse.urlsplit(uri)
71 authority = authority.encode('idna')
72 # For each character in 'ucschar' or 'iprivate'
74 # 2. then %-encode each octet of that utf-8
75 uri = urlparse.urlunsplit((scheme, authority, path, query, fragment))
76 uri = "".join([encode(c) for c in uri])
79 if __name__ == "__main__":
82 class Test(unittest.TestCase):
85 """Test that URIs are invariant under the transformation."""
87 u"ftp://ftp.is.co.za/rfc/rfc1808.txt",
88 u"http://www.ietf.org/rfc/rfc2396.txt",
89 u"ldap://[2001:db8::7]/c=GB?objectClass?one",
90 u"mailto:John.Doe@example.com",
91 u"news:comp.infosystems.www.servers.unix",
92 u"tel:+1-816-555-1212",
93 u"telnet://192.0.2.16:80/",
94 u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ]
96 self.assertEqual(uri, iri2uri(uri))
99 """ Test that the right type of escaping is done for each part of the URI."""
100 self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}"))
101 self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}"))
102 self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}"))
103 self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}"))
104 self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))
105 self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")))
106 self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8')))