當前位置: 首頁>>代碼示例>>Python>>正文


Python idna.encode方法代碼示例

本文整理匯總了Python中idna.encode方法的典型用法代碼示例。如果您正苦於以下問題:Python idna.encode方法的具體用法?Python idna.encode怎麽用?Python idna.encode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在idna的用法示例。


在下文中一共展示了idna.encode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _idna_encode

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def _idna_encode(name):
    if name and any([ord(x) > 128 for x in name]):
        try:
            import idna
        except ImportError:
            six.raise_from(
                LocationParseError("Unable to parse URL without the 'idna' module"),
                None,
            )
        try:
            return idna.encode(name.lower(), strict=True, std3_rules=True)
        except idna.IDNAError:
            six.raise_from(
                LocationParseError(u"Name '%s' is not a valid IDNA label" % name), None
            )
    return name.lower().encode("ascii") 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:18,代碼來源:url.py

示例2: wrap_socket

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def wrap_socket(self, sock, server_side=False,
                    do_handshake_on_connect=True, suppress_ragged_eofs=True,
                    server_hostname=None):
        cnx = OpenSSL.SSL.Connection(self._ctx, sock)

        if isinstance(server_hostname, six.text_type):  # Platform-specific: Python 3
            server_hostname = server_hostname.encode('utf-8')

        if server_hostname is not None:
            cnx.set_tlsext_host_name(server_hostname)

        cnx.set_connect_state()

        while True:
            try:
                cnx.do_handshake()
            except OpenSSL.SSL.WantReadError:
                if not util.wait_for_read(sock, sock.gettimeout()):
                    raise timeout('select timed out')
                continue
            except OpenSSL.SSL.Error as e:
                raise ssl.SSLError('bad handshake: %r' % e)
            break

        return WrappedSocket(cnx, sock) 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:27,代碼來源:pyopenssl.py

示例3: _encode_params

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def _encode_params(data):
        """Encode parameters in a piece of data.

        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
        if parameters are supplied as a dict.
        """

        if isinstance(data, (str, bytes)):
            return data
        elif hasattr(data, 'read'):
            return data
        elif hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data):
                if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
                    vs = [vs]
                for v in vs:
                    if v is not None:
                        result.append(
                            (k.encode('utf-8') if isinstance(k, str) else k,
                             v.encode('utf-8') if isinstance(v, str) else v))
            return urlencode(result, doseq=True)
        else:
            return data 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:27,代碼來源:models.py

示例4: __init__

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def __init__(self, hostname):
        """
        :type hostname: `unicode`
        """
        if not isinstance(hostname, text_type):
            raise TypeError("DNS-ID must be a unicode string.")

        hostname = hostname.strip()
        if hostname == u"" or _is_ip_address(hostname):
            raise ValueError("Invalid DNS-ID.")

        if any(ord(c) > 127 for c in hostname):
            if idna:
                ascii_id = idna.encode(hostname)
            else:
                raise ImportError(
                    "idna library is required for non-ASCII IDs."
                )
        else:
            ascii_id = hostname.encode("ascii")

        self.hostname = ascii_id.translate(_TRANS_TO_LOWER)
        if self._RE_LEGAL_CHARS.match(self.hostname) is None:
            raise ValueError("Invalid DNS-ID.") 
開發者ID:pyca,項目名稱:service-identity,代碼行數:26,代碼來源:_common.py

示例5: __init__

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def __init__(self, value):
        if not isinstance(value, six.text_type):
            raise TypeError("value must be a unicode string")

        name, address = parseaddr(value)
        parts = address.split(u"@")
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")
        elif len(parts) == 1:
            # Single label email name. This is valid for local delivery.
            # No IDNA encoding needed since there is no domain component.
            encoded = address.encode("ascii")
        else:
            # A normal email of the form user@domain.com. Let's attempt to
            # encode the domain component and reconstruct the address.
            encoded = parts[0].encode("ascii") + b"@" + idna.encode(parts[1])

        self._value = value
        self._encoded = encoded 
開發者ID:aliyun,項目名稱:oss-ftp,代碼行數:23,代碼來源:general_name.py

示例6: wrap_socket

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def wrap_socket(
        self,
        sock,
        server_side=False,
        do_handshake_on_connect=True,
        suppress_ragged_eofs=True,
        server_hostname=None,
    ):
        cnx = OpenSSL.SSL.Connection(self._ctx, sock)

        if isinstance(server_hostname, six.text_type):  # Platform-specific: Python 3
            server_hostname = server_hostname.encode("utf-8")

        if server_hostname is not None:
            cnx.set_tlsext_host_name(server_hostname)

        cnx.set_connect_state()

        while True:
            try:
                cnx.do_handshake()
            except OpenSSL.SSL.WantReadError:
                if not util.wait_for_read(sock, sock.gettimeout()):
                    raise timeout("select timed out")
                continue
            except OpenSSL.SSL.Error as e:
                raise ssl.SSLError("bad handshake: %r" % e)
            break

        return WrappedSocket(cnx, sock) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:32,代碼來源:pyopenssl.py

示例7: get_object

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def get_object(self, **kwargs):
        qs = self.get_queryset(**kwargs)
        domain = self.kwargs['domain']
        # support IDN domains, i.e. accept Unicode encoding too
        try:
            import idna
            if domain.startswith("*."):
                ace_domain = "*." + idna.encode(domain[2:]).decode("utf-8", "strict")
            else:
                ace_domain = idna.encode(domain).decode("utf-8", "strict")
        except:
            ace_domain = domain
        return get_object_or_404(qs, domain=ace_domain) 
開發者ID:deis,項目名稱:controller,代碼行數:15,代碼來源:views.py

示例8: _dnsname_to_stdlib

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def _dnsname_to_stdlib(name):
    """
    Converts a dNSName SubjectAlternativeName field to the form used by the
    standard library on the given Python version.

    Cryptography produces a dNSName as a unicode string that was idna-decoded
    from ASCII bytes. We need to idna-encode that string to get it back, and
    then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
    uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).

    If the name cannot be idna-encoded then we return None signalling that
    the name given should be skipped.
    """
    def idna_encode(name):
        """
        Borrowed wholesale from the Python Cryptography Project. It turns out
        that we can't just safely call `idna.encode`: it can explode for
        wildcard names. This avoids that problem.
        """
        import idna

        try:
            for prefix in [u'*.', u'.']:
                if name.startswith(prefix):
                    name = name[len(prefix):]
                    return prefix.encode('ascii') + idna.encode(name)
            return idna.encode(name)
        except idna.core.IDNAError:
            return None

    if ':' in name:
        return name

    name = idna_encode(name)
    if name is None:
        return None
    elif sys.version_info >= (3, 0):
        name = name.decode('utf-8')
    return name 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:41,代碼來源:pyopenssl.py

示例9: set_ciphers

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def set_ciphers(self, ciphers):
        if isinstance(ciphers, six.text_type):
            ciphers = ciphers.encode('utf-8')
        self._ctx.set_cipher_list(ciphers) 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:6,代碼來源:pyopenssl.py

示例10: load_verify_locations

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def load_verify_locations(self, cafile=None, capath=None, cadata=None):
        if cafile is not None:
            cafile = cafile.encode('utf-8')
        if capath is not None:
            capath = capath.encode('utf-8')
        self._ctx.load_verify_locations(cafile, capath)
        if cadata is not None:
            self._ctx.load_verify_locations(BytesIO(cadata)) 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:10,代碼來源:pyopenssl.py

示例11: _encode_invalid_chars

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"):
    """Percent-encodes a URI component without reapplying
    onto an already percent-encoded component.
    """
    if component is None:
        return component

    component = six.ensure_text(component)

    # Try to see if the component we're encoding is already percent-encoded
    # so we can skip all '%' characters but still encode all others.
    percent_encodings = PERCENT_RE.findall(component)

    # Normalize existing percent-encoded bytes.
    for enc in percent_encodings:
        if not enc.isupper():
            component = component.replace(enc, enc.upper())

    uri_bytes = component.encode("utf-8", "surrogatepass")
    is_percent_encoded = len(percent_encodings) == uri_bytes.count(b"%")

    encoded_component = bytearray()

    for i in range(0, len(uri_bytes)):
        # Will return a single character bytestring on both Python 2 & 3
        byte = uri_bytes[i : i + 1]
        byte_ord = ord(byte)
        if (is_percent_encoded and byte == b"%") or (
            byte_ord < 128 and byte.decode() in allowed_chars
        ):
            encoded_component.extend(byte)
            continue
        encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper()))

    return encoded_component.decode(encoding) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:37,代碼來源:url.py

示例12: _dnsname_to_stdlib

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def _dnsname_to_stdlib(name):
    """
    Converts a dNSName SubjectAlternativeName field to the form used by the
    standard library on the given Python version.

    Cryptography produces a dNSName as a unicode string that was idna-decoded
    from ASCII bytes. We need to idna-encode that string to get it back, and
    then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
    uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).

    If the name cannot be idna-encoded then we return None signalling that
    the name given should be skipped.
    """

    def idna_encode(name):
        """
        Borrowed wholesale from the Python Cryptography Project. It turns out
        that we can't just safely call `idna.encode`: it can explode for
        wildcard names. This avoids that problem.
        """
        import idna

        try:
            for prefix in [u"*.", u"."]:
                if name.startswith(prefix):
                    name = name[len(prefix) :]
                    return prefix.encode("ascii") + idna.encode(name)
            return idna.encode(name)
        except idna.core.IDNAError:
            return None

    # Don't send IPv6 addresses through the IDNA encoder.
    if ":" in name:
        return name

    name = idna_encode(name)
    if name is None:
        return None
    elif sys.version_info >= (3, 0):
        name = name.decode("utf-8")
    return name 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:43,代碼來源:pyopenssl.py

示例13: set_ciphers

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def set_ciphers(self, ciphers):
        if isinstance(ciphers, six.text_type):
            ciphers = ciphers.encode("utf-8")
        self._ctx.set_cipher_list(ciphers) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:6,代碼來源:pyopenssl.py

示例14: load_verify_locations

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def load_verify_locations(self, cafile=None, capath=None, cadata=None):
        if cafile is not None:
            cafile = cafile.encode("utf-8")
        if capath is not None:
            capath = capath.encode("utf-8")
        self._ctx.load_verify_locations(cafile, capath)
        if cadata is not None:
            self._ctx.load_verify_locations(BytesIO(cadata)) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:10,代碼來源:pyopenssl.py

示例15: _get_idna_encoded_host

# 需要導入模塊: import idna [as 別名]
# 或者: from idna import encode [as 別名]
def _get_idna_encoded_host(host):
        import idna

        try:
            host = idna.encode(host, uts46=True).decode('utf-8')
        except idna.IDNAError:
            raise UnicodeError
        return host 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:10,代碼來源:models.py


注:本文中的idna.encode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。