当前位置: 首页>>代码示例>>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;未经允许,请勿转载。