Change an IRI (internationalized R) to an URI.

    Used at MambuStruct.connect() method for any requests done to Mambu.

    Perfect example of unicode getting in the way.

    Illustrative (I hope) example: I have Mambu usernames with special
    chars in them. When retrieving them and then trying to build a
    MambuUser object with them, I get a BIG problem because of the
    unicode chars there. Using this I solved the problem.

def iriToUri(iri):
    """Change an IRI (internationalized R) to an URI.

    Used at MambuStruct.connect() method for any requests done to Mambu.

    Perfect example of unicode getting in the way.

    Illustrative (I hope) example: I have Mambu usernames with special
    chars in them. When retrieving them and then trying to build a
    MambuUser object with them, I get a BIG problem because of the
    unicode chars there. Using this I solved the problem.
    """
    def urlEncodeNonAscii(b):
        """Encode Non ASCII chars to URL-friendly chars.

        Sometimes unicode gets in the way. A shame, I know. And perhaps the
        biggest shame is not me correctly handling it.
        """
        import re
        return re.sub('[\x80-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), b)

    parts = urlparse.urlparse(iri)
    if sys.version_info < (3, 0):
        # python2
        partes = []
        for parti, part in enumerate(parts):
            try:
                if parti != 1:
                    partes.append(urlEncodeNonAscii(part.encode('utf-8')))
                else:
                    partes.append(part.encode('idna'))
            except UnicodeDecodeError as ue:
                partes.append(urlEncodeNonAscii(part.decode('latin')))
            except Exception as e:
                raise e
        return urlparse.urlunparse(partes)
    else:
        # python3
        uri = [part.decode('utf8') for parti, part in enumerate(parts.encode('utf8'))]
        return urlparse.urlunparse(uri)