Created
January 20, 2013 03:15
-
-
Save mnot/4576470 to your computer and use it in GitHub Desktop.
Convert an IRI to a URI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib | |
import urlparse | |
def iri_to_uri(iri, encoding='Latin-1'): | |
"Takes a Unicode string that can contain an IRI and emits a URI." | |
scheme, authority, path, query, frag = urlparse.urlsplit(iri) | |
scheme = scheme.encode(encoding) | |
if ":" in authority: | |
host, port = authority.split(":", 1) | |
authority = host.encode('idna') + ":%s" % port | |
else: | |
authority = authority.encode(encoding) | |
path = urllib.quote( | |
path.encode(encoding), | |
safe="/;%[]=:$&()+,!?*@'~" | |
) | |
query = urllib.quote( | |
query.encode(encoding), | |
safe="/;%[]=:$&()+,!?*@'~" | |
) | |
frag = urllib.quote( | |
frag.encode(encoding), | |
safe="/;%[]=:$&()+,!?*@'~" | |
) | |
return urlparse.urlunsplit((scheme, authority, path, query, frag)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment