Skip to content

Instantly share code, notes, and snippets.

@mnot
Created January 20, 2013 03:15
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnot/4576470 to your computer and use it in GitHub Desktop.
Save mnot/4576470 to your computer and use it in GitHub Desktop.
Convert an IRI to a URI
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