code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from . import common, pkcs1, transform def mgf1(seed: bytes, length: int, hasher: str = "SHA-1") -> bytes: """ MGF1 is a Mask Generation Function based on a hash function. A mask generation function takes an octet string of variable length and a desired output length as input, and outputs an octet string of the desired length. The plaintext-awareness of RSAES-OAEP relies on the random nature of the output of the mask generation function, which in turn relies on the random nature of the underlying hash. :param bytes seed: seed from which mask is generated, an octet string :param int length: intended length in octets of the mask, at most 2^32(hLen) :param str hasher: hash function (hLen denotes the length in octets of the hash function output) :return: mask, an octet string of length `length` :rtype: bytes :raise OverflowError: when `length` is too large for the specified `hasher` :raise ValueError: when specified `hasher` is invalid """ try: hash_length = pkcs1.HASH_METHODS[hasher]().digest_size except KeyError as ex: raise ValueError( "Invalid `hasher` specified. Please select one of: {hash_list}".format( hash_list=", ".join(sorted(pkcs1.HASH_METHODS.keys())) ) ) from ex # If l > 2^32(hLen), output "mask too long" and stop. if length > (2 ** 32 * hash_length): raise OverflowError( "Desired length should be at most 2**32 times the hasher's output " "length ({hash_length} for {hasher} function)".format( hash_length=hash_length, hasher=hasher, ) ) # Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the # hashes formed by (`seed` + C), being `C` an octet string of length 4 # generated by converting `counter` with the primitive I2OSP output = b"".join( pkcs1.compute_hash( seed + transform.int2bytes(counter, fill_size=4), method_name=hasher, ) for counter in range(common.ceil_div(length, hash_length) + 1) ) # Output the leading `length` octets of `output` as the octet string mask. return output[:length] __all__ = [ "mgf1", ] if __name__ == "__main__": print("Running doctests 1000x or until failure") import doctest for count in range(1000): (failures, tests) = doctest.testmod() if failures: break if count % 100 == 0 and count: print("%i times" % count) print("Doctests done")
zdppy-password
/zdppy_password-0.1.0-py3-none-any.whl/zdppy_password/libs/rsa/pkcs1_v2.py
pkcs1_v2.py
import logging import threading import typing import warnings from . import prime, pem, common, randnum, core log = logging.getLogger(__name__) DEFAULT_EXPONENT = 65537 class AbstractKey: """Abstract superclass for private and public keys.""" __slots__ = ("n", "e", "blindfac", "blindfac_inverse", "mutex") def __init__(self, n: int, e: int) -> None: self.n = n self.e = e # These will be computed properly on the first call to blind(). self.blindfac = self.blindfac_inverse = -1 # Used to protect updates to the blinding factor in multi-threaded # environments. self.mutex = threading.Lock() @classmethod def _load_pkcs1_pem(cls, keyfile: bytes) -> "AbstractKey": """Loads a key in PKCS#1 PEM format, implement in a subclass. :param keyfile: contents of a PEM-encoded file that contains the public key. :type keyfile: bytes :return: the loaded key :rtype: AbstractKey """ @classmethod def _load_pkcs1_der(cls, keyfile: bytes) -> "AbstractKey": """Loads a key in PKCS#1 PEM format, implement in a subclass. :param keyfile: contents of a DER-encoded file that contains the public key. :type keyfile: bytes :return: the loaded key :rtype: AbstractKey """ def _save_pkcs1_pem(self) -> bytes: """Saves the key in PKCS#1 PEM format, implement in a subclass. :returns: the PEM-encoded key. :rtype: bytes """ def _save_pkcs1_der(self) -> bytes: """Saves the key in PKCS#1 DER format, implement in a subclass. :returns: the DER-encoded key. :rtype: bytes """ @classmethod def load_pkcs1(cls, keyfile: bytes, format: str = "PEM") -> "AbstractKey": """Loads a key in PKCS#1 DER or PEM format. :param keyfile: contents of a DER- or PEM-encoded file that contains the key. :type keyfile: bytes :param format: the format of the file to load; 'PEM' or 'DER' :type format: str :return: the loaded key :rtype: AbstractKey """ methods = { "PEM": cls._load_pkcs1_pem, "DER": cls._load_pkcs1_der, } method = cls._assert_format_exists(format, methods) return method(keyfile) @staticmethod def _assert_format_exists( file_format: str, methods: typing.Mapping[str, typing.Callable] ) -> typing.Callable: """Checks whether the given file format exists in 'methods'.""" try: return methods[file_format] except KeyError as ex: formats = ", ".join(sorted(methods.keys())) raise ValueError( "Unsupported format: %r, try one of %s" % (file_format, formats) ) from ex def save_pkcs1(self, format: str = "PEM") -> bytes: """Saves the key in PKCS#1 DER or PEM format. :param format: the format to save; 'PEM' or 'DER' :type format: str :returns: the DER- or PEM-encoded key. :rtype: bytes """ methods = { "PEM": self._save_pkcs1_pem, "DER": self._save_pkcs1_der, } method = self._assert_format_exists(format, methods) return method() def blind(self, message: int) -> typing.Tuple[int, int]: """Performs blinding on the message. :param message: the message, as integer, to blind. :param r: the random number to blind with. :return: tuple (the blinded message, the inverse of the used blinding factor) The blinding is such that message = unblind(decrypt(blind(encrypt(message))). See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29 """ blindfac, blindfac_inverse = self._update_blinding_factor() blinded = (message * pow(blindfac, self.e, self.n)) % self.n return blinded, blindfac_inverse def unblind(self, blinded: int, blindfac_inverse: int) -> int: """Performs blinding on the message using random number 'blindfac_inverse'. :param blinded: the blinded message, as integer, to unblind. :param blindfac: the factor to unblind with. :return: the original message. The blinding is such that message = unblind(decrypt(blind(encrypt(message))). See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29 """ return (blindfac_inverse * blinded) % self.n def _initial_blinding_factor(self) -> int: for _ in range(1000): blind_r = randnum.randint(self.n - 1) if prime.are_relatively_prime(self.n, blind_r): return blind_r raise RuntimeError("unable to find blinding factor") def _update_blinding_factor(self) -> typing.Tuple[int, int]: """Update blinding factors. Computing a blinding factor is expensive, so instead this function does this once, then updates the blinding factor as per section 9 of 'A Timing Attack against RSA with the Chinese Remainder Theorem' by Werner Schindler. See https://tls.mbed.org/public/WSchindler-RSA_Timing_Attack.pdf :return: the new blinding factor and its inverse. """ with self.mutex: if self.blindfac < 0: # Compute initial blinding factor, which is rather slow to do. self.blindfac = self._initial_blinding_factor() self.blindfac_inverse = common.inverse(self.blindfac, self.n) else: # Reuse previous blinding factor. self.blindfac = pow(self.blindfac, 2, self.n) self.blindfac_inverse = pow(self.blindfac_inverse, 2, self.n) return self.blindfac, self.blindfac_inverse class PublicKey(AbstractKey): """Represents a public RSA key. This key is also known as the 'encryption key'. It contains the 'n' and 'e' values. Supports attributes as well as dictionary-like access. Attribute access is faster, though. >>> PublicKey(5, 3) PublicKey(5, 3) >>> key = PublicKey(5, 3) >>> key.n 5 >>> key['n'] 5 >>> key.e 3 >>> key['e'] 3 """ __slots__ = ("n", "e") def __getitem__(self, key: str) -> int: return getattr(self, key) def __repr__(self) -> str: return "PublicKey(%i, %i)" % (self.n, self.e) def __getstate__(self) -> typing.Tuple[int, int]: """Returns the key as tuple for pickling.""" return self.n, self.e def __setstate__(self, state: typing.Tuple[int, int]) -> None: """Sets the key from tuple.""" self.n, self.e = state AbstractKey.__init__(self, self.n, self.e) def __eq__(self, other: typing.Any) -> bool: if other is None: return False if not isinstance(other, PublicKey): return False return self.n == other.n and self.e == other.e def __ne__(self, other: typing.Any) -> bool: return not (self == other) def __hash__(self) -> int: return hash((self.n, self.e)) @classmethod def _load_pkcs1_der(cls, keyfile: bytes) -> "PublicKey": """Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the public key. :return: a PublicKey object First let's construct a DER encoded key: >>> import base64 >>> b64der = 'MAwCBQCNGmYtAgMBAAE=' >>> der = base64.standard_b64decode(b64der) This loads the file: >>> PublicKey._load_pkcs1_der(der) PublicKey(2367317549, 65537) """ from pyasn1.codec.der import decoder from asn1 import AsnPubKey (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey()) return cls(n=int(priv["modulus"]), e=int(priv["publicExponent"])) def _save_pkcs1_der(self) -> bytes: """Saves the public key in PKCS#1 DER format. :returns: the DER-encoded public key. :rtype: bytes """ from pyasn1.codec.der import encoder from asn1 import AsnPubKey # Create the ASN object asn_key = AsnPubKey() asn_key.setComponentByName("modulus", self.n) asn_key.setComponentByName("publicExponent", self.e) return encoder.encode(asn_key) @classmethod def _load_pkcs1_pem(cls, keyfile: bytes) -> "PublicKey": """Loads a PKCS#1 PEM-encoded public key file. The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and after the "-----END RSA PUBLIC KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the public key. :return: a PublicKey object """ der = pem.load_pem(keyfile, "RSA PUBLIC KEY") return cls._load_pkcs1_der(der) def _save_pkcs1_pem(self) -> bytes: """Saves a PKCS#1 PEM-encoded public key file. :return: contents of a PEM-encoded file that contains the public key. :rtype: bytes """ der = self._save_pkcs1_der() return pem.save_pem(der, "RSA PUBLIC KEY") @classmethod def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> "PublicKey": """Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL. These files can be recognised in that they start with BEGIN PUBLIC KEY rather than BEGIN RSA PUBLIC KEY. The contents of the file before the "-----BEGIN PUBLIC KEY-----" and after the "-----END PUBLIC KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the public key, from OpenSSL. :type keyfile: bytes :return: a PublicKey object """ der = pem.load_pem(keyfile, "PUBLIC KEY") return cls.load_pkcs1_openssl_der(der) @classmethod def load_pkcs1_openssl_der(cls, keyfile: bytes) -> "PublicKey": """Loads a PKCS#1 DER-encoded public key file from OpenSSL. :param keyfile: contents of a DER-encoded file that contains the public key, from OpenSSL. :return: a PublicKey object """ from asn1 import OpenSSLPubKey from pyasn1.codec.der import decoder from pyasn1.type import univ (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey()) if keyinfo["header"]["oid"] != univ.ObjectIdentifier("1.2.840.113549.1.1.1"): raise TypeError("This is not a DER-encoded OpenSSL-compatible public key") return cls._load_pkcs1_der(keyinfo["key"][1:]) class PrivateKey(AbstractKey): """Represents a private RSA key. This key is also known as the 'decryption key'. It contains the 'n', 'e', 'd', 'p', 'q' and other values. Supports attributes as well as dictionary-like access. Attribute access is faster, though. >>> PrivateKey(3247, 65537, 833, 191, 17) PrivateKey(3247, 65537, 833, 191, 17) exp1, exp2 and coef will be calculated: >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287) >>> pk.exp1 55063 >>> pk.exp2 10095 >>> pk.coef 50797 """ __slots__ = ("n", "e", "d", "p", "q", "exp1", "exp2", "coef") def __init__(self, n: int, e: int, d: int, p: int, q: int) -> None: AbstractKey.__init__(self, n, e) self.d = d self.p = p self.q = q # Calculate exponents and coefficient. self.exp1 = int(d % (p - 1)) self.exp2 = int(d % (q - 1)) self.coef = common.inverse(q, p) def __getitem__(self, key: str) -> int: return getattr(self, key) def __repr__(self) -> str: return "PrivateKey(%i, %i, %i, %i, %i)" % ( self.n, self.e, self.d, self.p, self.q, ) def __getstate__(self) -> typing.Tuple[int, int, int, int, int, int, int, int]: """Returns the key as tuple for pickling.""" return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef def __setstate__(self, state: typing.Tuple[int, int, int, int, int, int, int, int]) -> None: """Sets the key from tuple.""" self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state AbstractKey.__init__(self, self.n, self.e) def __eq__(self, other: typing.Any) -> bool: if other is None: return False if not isinstance(other, PrivateKey): return False return ( self.n == other.n and self.e == other.e and self.d == other.d and self.p == other.p and self.q == other.q and self.exp1 == other.exp1 and self.exp2 == other.exp2 and self.coef == other.coef ) def __ne__(self, other: typing.Any) -> bool: return not (self == other) def __hash__(self) -> int: return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)) def blinded_decrypt(self, encrypted: int) -> int: """ 使用盲法解密消息,以防止侧通道攻击。 :param encrypted: the encrypted message :type encrypted: int :returns: the decrypted message :rtype: int """ # Blinding and un-blinding should be using the same factor blinded, blindfac_inverse = self.blind(encrypted) # Instead of using the core functionality, use the Chinese Remainder # Theorem and be 2-4x faster. This the same as: # # decrypted = core.decrypt_int(blinded, self.d, self.n) s1 = pow(blinded, self.exp1, self.p) s2 = pow(blinded, self.exp2, self.q) h = ((s1 - s2) * self.coef) % self.p decrypted = s2 + self.q * h return self.unblind(decrypted, blindfac_inverse) def blinded_encrypt(self, message: int) -> int: """Encrypts the message using blinding to prevent side-channel attacks. :param message: the message to encrypt :type message: int :returns: the encrypted message :rtype: int """ blinded, blindfac_inverse = self.blind(message) encrypted = core.encrypt_int(blinded, self.d, self.n) return self.unblind(encrypted, blindfac_inverse) @classmethod def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey": """Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the private key. :type keyfile: bytes :return: a PrivateKey object First let's construct a DER encoded key: >>> import base64 >>> b64der = 'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt' >>> der = base64.standard_b64decode(b64der) This loads the file: >>> PrivateKey._load_pkcs1_der(der) PrivateKey(3727264081, 65537, 3349121513, 65063, 57287) """ from pyasn1.codec.der import decoder (priv, _) = decoder.decode(keyfile) # ASN.1 contents of DER encoded private key: # # RSAPrivateKey ::= SEQUENCE { # version Version, # modulus INTEGER, -- n # publicExponent INTEGER, -- e # privateExponent INTEGER, -- d # prime1 INTEGER, -- p # prime2 INTEGER, -- q # exponent1 INTEGER, -- d mod (p-1) # exponent2 INTEGER, -- d mod (q-1) # coefficient INTEGER, -- (inverse of q) mod p # otherPrimeInfos OtherPrimeInfos OPTIONAL # } if priv[0] != 0: raise ValueError("Unable to read this file, version %s != 0" % priv[0]) as_ints = map(int, priv[1:6]) key = cls(*as_ints) exp1, exp2, coef = map(int, priv[6:9]) if (key.exp1, key.exp2, key.coef) != (exp1, exp2, coef): warnings.warn( "You have provided a malformed keyfile. Either the exponents " "or the coefficient are incorrect. Using the correct values " "instead.", UserWarning, ) return key def _save_pkcs1_der(self) -> bytes: """Saves the private key in PKCS#1 DER format. :returns: the DER-encoded private key. :rtype: bytes """ from pyasn1.type import univ, namedtype from pyasn1.codec.der import encoder class AsnPrivKey(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType("version", univ.Integer()), namedtype.NamedType("modulus", univ.Integer()), namedtype.NamedType("publicExponent", univ.Integer()), namedtype.NamedType("privateExponent", univ.Integer()), namedtype.NamedType("prime1", univ.Integer()), namedtype.NamedType("prime2", univ.Integer()), namedtype.NamedType("exponent1", univ.Integer()), namedtype.NamedType("exponent2", univ.Integer()), namedtype.NamedType("coefficient", univ.Integer()), ) # Create the ASN object asn_key = AsnPrivKey() asn_key.setComponentByName("version", 0) asn_key.setComponentByName("modulus", self.n) asn_key.setComponentByName("publicExponent", self.e) asn_key.setComponentByName("privateExponent", self.d) asn_key.setComponentByName("prime1", self.p) asn_key.setComponentByName("prime2", self.q) asn_key.setComponentByName("exponent1", self.exp1) asn_key.setComponentByName("exponent2", self.exp2) asn_key.setComponentByName("coefficient", self.coef) return encoder.encode(asn_key) @classmethod def _load_pkcs1_pem(cls, keyfile: bytes) -> "PrivateKey": """Loads a PKCS#1 PEM-encoded private key file. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and after the "-----END RSA PRIVATE KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the private key. :type keyfile: bytes :return: a PrivateKey object """ der = pem.load_pem(keyfile, b"RSA PRIVATE KEY") return cls._load_pkcs1_der(der) def _save_pkcs1_pem(self) -> bytes: """Saves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key. :rtype: bytes """ der = self._save_pkcs1_der() return pem.save_pem(der, b"RSA PRIVATE KEY") def find_p_q( nbits: int, getprime_func: typing.Callable[[int], int] = prime.getprime, accurate: bool = True, ) -> typing.Tuple[int, int]: """Returns a tuple of two different primes of nbits bits each. The resulting p * q has exactly 2 * nbits bits, and the returned p and q will not be equal. :param nbits: the number of bits in each of p and q. :param getprime_func: the getprime function, defaults to :py:func:`prime.getprime`. *Introduced in Python-RSA 3.1* :param accurate: whether to enable accurate mode or not. :returns: (p, q), where p > q >>> (p, q) = find_p_q(128) >>> from rsa import common >>> common.bit_size(p * q) 256 When not in accurate mode, the number of bits can be slightly less >>> (p, q) = find_p_q(128, accurate=False) >>> from rsa import common >>> common.bit_size(p * q) <= 256 True >>> common.bit_size(p * q) > 240 True """ total_bits = nbits * 2 # Make sure that p and q aren't too close or the factoring programs can # factor n. shift = nbits // 16 pbits = nbits + shift qbits = nbits - shift # Choose the two initial primes log.debug("find_p_q(%i): Finding p", nbits) p = getprime_func(pbits) log.debug("find_p_q(%i): Finding q", nbits) q = getprime_func(qbits) def is_acceptable(p: int, q: int) -> bool: """Returns True iff p and q are acceptable: - p and q differ - (p * q) has the right nr of bits (when accurate=True) """ if p == q: return False if not accurate: return True # Make sure we have just the right amount of bits found_size = common.bit_size(p * q) return total_bits == found_size # Keep choosing other primes until they match our requirements. change_p = False while not is_acceptable(p, q): # Change p on one iteration and q on the other if change_p: p = getprime_func(pbits) else: q = getprime_func(qbits) change_p = not change_p # We want p > q as described on # http://www.di-mgt.com.au/rsa_alg.html#crt return max(p, q), min(p, q) def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> typing.Tuple[int, int]: """Calculates an encryption and a decryption key given p, q and an exponent, and returns them as a tuple (e, d) :param p: the first large prime :param q: the second large prime :param exponent: the exponent for the key; only change this if you know what you're doing, as the exponent influences how difficult your private key can be cracked. A very common choice for e is 65537. :type exponent: int """ phi_n = (p - 1) * (q - 1) try: d = common.inverse(exponent, phi_n) except common.NotRelativePrimeError as ex: raise common.NotRelativePrimeError( exponent, phi_n, ex.d, msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)" % (exponent, phi_n, ex.d), ) from ex if (exponent * d) % phi_n != 1: raise ValueError( "e (%d) and d (%d) are not mult. inv. modulo " "phi_n (%d)" % (exponent, d, phi_n) ) return exponent, d def calculate_keys(p: int, q: int) -> typing.Tuple[int, int]: """Calculates an encryption and a decryption key given p and q, and returns them as a tuple (e, d) :param p: the first large prime :param q: the second large prime :return: tuple (e, d) with the encryption and decryption exponents. """ return calculate_keys_custom_exponent(p, q, DEFAULT_EXPONENT) def gen_keys( nbits: int, getprime_func: typing.Callable[[int], int], accurate: bool = True, exponent: int = DEFAULT_EXPONENT, ) -> typing.Tuple[int, int, int, int]: """Generate RSA keys of nbits bits. Returns (p, q, e, d). Note: this can take a long time, depending on the key size. :param nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and ``q`` will use ``nbits/2`` bits. :param getprime_func: either :py:func:`prime.getprime` or a function with similar signature. :param exponent: the exponent for the key; only change this if you know what you're doing, as the exponent influences how difficult your private key can be cracked. A very common choice for e is 65537. :type exponent: int """ # Regenerate p and q values, until calculate_keys doesn't raise a # ValueError. while True: (p, q) = find_p_q(nbits // 2, getprime_func, accurate) try: (e, d) = calculate_keys_custom_exponent(p, q, exponent=exponent) break except ValueError: pass return p, q, e, d def newkeys( nbits: int, accurate: bool = True, poolsize: int = 1, exponent: int = DEFAULT_EXPONENT, ) -> typing.Tuple[PublicKey, PrivateKey]: """Generates public and private keys, and returns them as (pub, priv). The public key is also known as the 'encryption key', and is a :py:class:`PublicKey` object. The private key is also known as the 'decryption key' and is a :py:class:`PrivateKey` object. :param nbits: the number of bits required to store ``n = p*q``. :param accurate: when True, ``n`` will have exactly the number of bits you asked for. However, this makes key generation much slower. When False, `n`` may have slightly less bits. :param poolsize: the number of processes to use to generate the prime numbers. If set to a number > 1, a parallel algorithm will be used. This requires Python 2.6 or newer. :param exponent: the exponent for the key; only change this if you know what you're doing, as the exponent influences how difficult your private key can be cracked. A very common choice for e is 65537. :type exponent: int :returns: a tuple (:py:class:`PublicKey`, :py:class:`PrivateKey`) The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires Python 2.6 or newer. """ if nbits < 16: raise ValueError("Key too small") if poolsize < 1: raise ValueError("Pool size (%i) should be >= 1" % poolsize) # Determine which getprime function to use if poolsize > 1: from rsa import parallel def getprime_func(nbits: int) -> int: return parallel.getprime(nbits, poolsize=poolsize) else: getprime_func = prime.getprime # Generate the key components (p, q, e, d) = gen_keys(nbits, getprime_func, accurate=accurate, exponent=exponent) # Create the key objects n = p * q return (PublicKey(n, e), PrivateKey(n, e, d, p, q)) __all__ = ["PublicKey", "PrivateKey", "newkeys"] if __name__ == "__main__": import doctest try: for count in range(100): (failures, tests) = doctest.testmod() if failures: break if (count % 10 == 0 and count) or count == 1: print("%i times" % count) except KeyboardInterrupt: print("Aborted") else: print("Doctests done")
zdppy-password
/zdppy_password-0.1.0-py3-none-any.whl/zdppy_password/libs/rsa/key.py
key.py
import abc import sys import typing import optparse from . import key, pkcs1 HASH_METHODS = sorted(pkcs1.HASH_METHODS.keys()) Indexable = typing.Union[typing.Tuple, typing.List[str]] def keygen() -> None: """Key generator.""" # Parse the CLI options parser = optparse.OptionParser( usage="usage: %prog [options] keysize", description='Generates a new RSA key pair of "keysize" bits.', ) parser.add_option( "--pubout", type="string", help="Output filename for the public key. The public key is " "not saved if this option is not present. You can use " "pyrsa-priv2pub to create the public key file later.", ) parser.add_option( "-o", "--out", type="string", help="Output filename for the private key. The key is " "written to stdout if this option is not present.", ) parser.add_option( "--form", help="key format of the private and public keys - default PEM", choices=("PEM", "DER"), default="PEM", ) (cli, cli_args) = parser.parse_args(sys.argv[1:]) if len(cli_args) != 1: parser.print_help() raise SystemExit(1) try: keysize = int(cli_args[0]) except ValueError as ex: parser.print_help() print("Not a valid number: %s" % cli_args[0], file=sys.stderr) raise SystemExit(1) from ex print("Generating %i-bit key" % keysize, file=sys.stderr) (pub_key, priv_key) = key.newkeys(keysize) # Save public key if cli.pubout: print("Writing public key to %s" % cli.pubout, file=sys.stderr) data = pub_key.save_pkcs1(format=cli.form) with open(cli.pubout, "wb") as outfile: outfile.write(data) # Save private key data = priv_key.save_pkcs1(format=cli.form) if cli.out: print("Writing private key to %s" % cli.out, file=sys.stderr) with open(cli.out, "wb") as outfile: outfile.write(data) else: print("Writing private key to stdout", file=sys.stderr) sys.stdout.buffer.write(data) class CryptoOperation(metaclass=abc.ABCMeta): """CLI callable that operates with input, output, and a key.""" keyname = "public" # or 'private' usage = "usage: %%prog [options] %(keyname)s_key" description = "" operation = "decrypt" operation_past = "decrypted" operation_progressive = "decrypting" input_help = "Name of the file to %(operation)s. Reads from stdin if " "not specified." output_help = ( "Name of the file to write the %(operation_past)s file " "to. Written to stdout if this option is not present." ) expected_cli_args = 1 has_output = True key_class = key.PublicKey # type: typing.Type[key.AbstractKey] def __init__(self) -> None: self.usage = self.usage % self.__class__.__dict__ self.input_help = self.input_help % self.__class__.__dict__ self.output_help = self.output_help % self.__class__.__dict__ @abc.abstractmethod def perform_operation( self, indata: bytes, key: key.AbstractKey, cli_args: Indexable ) -> typing.Any: """Performs the program's operation. Implement in a subclass. :returns: the data to write to the output. """ def __call__(self) -> None: """Runs the program.""" (cli, cli_args) = self.parse_cli() key = self.read_key(cli_args[0], cli.keyform) indata = self.read_infile(cli.input) print(self.operation_progressive.title(), file=sys.stderr) outdata = self.perform_operation(indata, key, cli_args) if self.has_output: self.write_outfile(outdata, cli.output) def parse_cli(self) -> typing.Tuple[optparse.Values, typing.List[str]]: """Parse the CLI options :returns: (cli_opts, cli_args) """ parser = optparse.OptionParser(usage=self.usage, description=self.description) parser.add_option("-i", "--input", type="string", help=self.input_help) if self.has_output: parser.add_option("-o", "--output", type="string", help=self.output_help) parser.add_option( "--keyform", help="Key format of the %s key - default PEM" % self.keyname, choices=("PEM", "DER"), default="PEM", ) (cli, cli_args) = parser.parse_args(sys.argv[1:]) if len(cli_args) != self.expected_cli_args: parser.print_help() raise SystemExit(1) return cli, cli_args def read_key(self, filename: str, keyform: str) -> key.AbstractKey: """Reads a public or private key.""" print("Reading %s key from %s" % (self.keyname, filename), file=sys.stderr) with open(filename, "rb") as keyfile: keydata = keyfile.read() return self.key_class.load_pkcs1(keydata, keyform) def read_infile(self, inname: str) -> bytes: """Read the input file""" if inname: print("Reading input from %s" % inname, file=sys.stderr) with open(inname, "rb") as infile: return infile.read() print("Reading input from stdin", file=sys.stderr) return sys.stdin.buffer.read() def write_outfile(self, outdata: bytes, outname: str) -> None: """Write the output file""" if outname: print("Writing output to %s" % outname, file=sys.stderr) with open(outname, "wb") as outfile: outfile.write(outdata) else: print("Writing output to stdout", file=sys.stderr) sys.stdout.buffer.write(outdata) class EncryptOperation(CryptoOperation): """Encrypts a file.""" keyname = "public" description = ( "Encrypts a file. The file must be shorter than the key " "length in order to be encrypted." ) operation = "encrypt" operation_past = "encrypted" operation_progressive = "encrypting" def perform_operation( self, indata: bytes, pub_key: key.AbstractKey, cli_args: Indexable = () ) -> bytes: """Encrypts files.""" assert isinstance(pub_key, key.PublicKey) return pkcs1.encrypt(indata, pub_key) class DecryptOperation(CryptoOperation): """Decrypts a file.""" keyname = "private" description = ( "Decrypts a file. The original file must be shorter than " "the key length in order to have been encrypted." ) operation = "decrypt" operation_past = "decrypted" operation_progressive = "decrypting" key_class = key.PrivateKey def perform_operation( self, indata: bytes, priv_key: key.AbstractKey, cli_args: Indexable = () ) -> bytes: """Decrypts files.""" assert isinstance(priv_key, key.PrivateKey) return pkcs1.decrypt(indata, priv_key) class SignOperation(CryptoOperation): """Signs a file.""" keyname = "private" usage = "usage: %%prog [options] private_key hash_method" description = ( "Signs a file, outputs the signature. Choose the hash " "method from %s" % ", ".join(HASH_METHODS) ) operation = "sign" operation_past = "signature" operation_progressive = "Signing" key_class = key.PrivateKey expected_cli_args = 2 output_help = ( "Name of the file to write the signature to. Written " "to stdout if this option is not present." ) def perform_operation( self, indata: bytes, priv_key: key.AbstractKey, cli_args: Indexable ) -> bytes: """Signs files.""" assert isinstance(priv_key, key.PrivateKey) hash_method = cli_args[1] if hash_method not in HASH_METHODS: raise SystemExit("Invalid hash method, choose one of %s" % ", ".join(HASH_METHODS)) return pkcs1.sign(indata, priv_key, hash_method) class VerifyOperation(CryptoOperation): """Verify a signature.""" keyname = "public" usage = "usage: %%prog [options] public_key signature_file" description = ( "Verifies a signature, exits with status 0 upon success, " "prints an error message and exits with status 1 upon error." ) operation = "verify" operation_past = "verified" operation_progressive = "Verifying" key_class = key.PublicKey expected_cli_args = 2 has_output = False def perform_operation( self, indata: bytes, pub_key: key.AbstractKey, cli_args: Indexable ) -> None: """Verifies files.""" assert isinstance(pub_key, key.PublicKey) signature_file = cli_args[1] with open(signature_file, "rb") as sigfile: signature = sigfile.read() try: pkcs1.verify(indata, signature, pub_key) except pkcs1.VerificationError as ex: raise SystemExit("Verification failed.") from ex print("Verification OK", file=sys.stderr) encrypt = EncryptOperation() decrypt = DecryptOperation() sign = SignOperation() verify = VerifyOperation()
zdppy-password
/zdppy_password-0.1.0-py3-none-any.whl/zdppy_password/libs/rsa/cli.py
cli.py
import json from typing import Dict, Union, Tuple, List from zdppy_log import Log import redis class Redis: def __init__(self, host: str = "localhost", port: int = 6379, database: int = 0, decode_responses: bool = True, encoding: str = "utf-8", max_connections: int = 10, log_file_path: str = "logs/zdppy/zdppy_log.log", config: Dict = {}, config_secret: Dict = {} ): """ 创建Redis核心对象 :param host: redis主机地址 :param port: redis端口号 :param database: redis数据库 :param decode_responses: 是否解析响应 :param encoding: 编码格式 :param max_connections: 最大连接数 :param log_file_path: 日志路径 :param config: 配置信息 :param config_secret: 私密配置信息 """ # 日志 self.log = Log(log_file_path) # redis核心对象 self.host = host self.port = port self.database = database self.decode_responses = decode_responses self.encoding = encoding self.max_connections = max_connections self.pool = None # 配置对象 self.config = {} self.config.update(config) self.config.update(config_secret) def update_config(self, config: Union[Dict, str, List, Tuple]): """ 读取配置信息 :param config:配置对象 :return: """ # 配置对象本身是一个字典 if isinstance(config, dict): self.config.update(config) # 配置对象是redis的key elif isinstance(config, str): c = json.loads(self.get(config)) if isinstance(c, dict): self.config.update(c) self.log.info(f"更新配置成功:{c}") else: self.log.error(f"更新配置失败,{config}不是字典类型:{c}") # 配置对象是redis的key列表 elif isinstance(config, list) or isinstance(config, tuple): for cl in config: c = json.loads(self.get(cl)) if isinstance(c, dict): self.config.update(c) self.log.info(f"更新配置成功:{c}") else: self.log.error(f"更新配置失败,{cl}不是字典类型:{c}") def save_config(self, config="zdppy_redis_config"): """ 保存配置 :param config: 配置的redis的key :return: """ self.set(config, json.dumps(self.config)) def get_db(self): """ 获取redis连接对象 :return: """ # 创建pool if self.pool is None: # 不存在则创建 url = f"redis://{self.host}:{self.port}/{self.database}" self.log.info(f"尝试与redis建立连接:{url}") self.pool = redis.ConnectionPool.from_url(url, encoding=self.encoding, decode_responses=self.decode_responses, max_connections=self.max_connections) self.log.info("与redis建立连接成功") db = redis.Redis(connection_pool=self.pool) return db def set(self, key, value, expire=60 * 60 * 30): """ 设置值 :param key: :param value: :return: """ # 设置值 db = self.get_db() db.set(key, value, px=expire) def get(self, key): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return db.get(key) def mset(self, kv_dict): """ 设置值 :param key: :param value: :return: """ # 设置值 db = self.get_db() db.mset(kv_dict) def mget(self, *keys): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return db.mget(*keys) def incr(self, key, amount=1): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return db.incr(key, amount=amount) def incrbyfloat(self, key, amount=1.0): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return db.incrbyfloat(key, amount=amount) async def delete(self, *keys): """ 删除key :param key: :return: """ # 获取值 db = self.get_db() return await db.delete(*keys) def hset(self, key, value): """ 设置hash内容 :return: """ # 设置hash内容 db = self.get_db() db.hset(key, mapping=value) def hgetall(self, key): """ 获取hash所有内容 :param key: :return: """ db = self.get_db() return db.hgetall(key) async def close(self): if self.pool is not None: await self.pool.disconnect()
zdppy-redis
/zdppy_redis-0.1.0-py3-none-any.whl/zdppy_redis/zdppy_redis.py
zdppy_redis.py
import aioredis from zdppy_log import Log from typing import Dict, Any import asyncio import async_timeout class AsyncRedis: def __init__(self, host: str = "localhost", port: int = 6379, database: int = 0, decode_responses: bool = True, encoding: str = "utf-8", max_connections: int = 10, log_file_path: str = "logs/zdppy/zdppy_log.log"): # 日志 self.log = Log(log_file_path) # redis核心对象 self.host = host self.port = port self.database = database self.decode_responses = decode_responses self.encoding = encoding self.max_connections = max_connections self.pool = None def get_db(self): """ 获取redis连接对象 :return: """ # 创建pool if self.pool is None: # 不存在则创建 url = f"redis://{self.host}:{self.port}/{self.database}" self.log.info(f"尝试与redis建立连接:{url}") self.pool = aioredis.ConnectionPool.from_url(url, encoding=self.encoding, decode_responses=self.decode_responses, max_connections=self.max_connections) self.log.info("与redis建立连接成功") db = aioredis.Redis(connection_pool=self.pool) return db async def set(self, key, value, expire=60 * 60 * 30): """ 设置值 :param key: :param value: :return: """ # 设置值 db = self.get_db() await db.set(key, value, px=expire) async def get(self, key): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return await db.get(key) async def mset(self, kv_dict): """ 设置值 :param key: :param value: :return: """ # 设置值 db = self.get_db() await db.mset(kv_dict) async def mget(self, *keys): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return await db.mget(*keys) async def incr(self, key, amount=1): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return await db.incr(key, amount=amount) async def incrbyfloat(self, key, amount=1.0): """ 获取值 :param key: :return: """ # 获取值 db = self.get_db() return await db.incrbyfloat(key, amount=amount) async def delete(self, *keys): """ 删除key :param key: :return: """ # 获取值 db = self.get_db() return await db.delete(*keys) async def hset(self, key, value): """ 设置hash内容 :return: """ # 设置hash内容 db = self.get_db() await db.hset(key, mapping=value) async def hgetall(self, key): """ 获取hash所有内容 :param key: :return: """ db = self.get_db() return await db.hgetall(key) async def close(self): if self.pool is not None: await self.pool.disconnect()
zdppy-redis
/zdppy_redis-0.1.0-py3-none-any.whl/zdppy_redis/async_redis.py
async_redis.py
r""" The ``codes`` object defines a mapping from common names for HTTP statuses to their numerical codes, accessible either as attributes or as dictionary items. Example:: >>> import requests >>> requests.codes['temporary_redirect'] 307 >>> requests.codes.teapot 418 >>> requests.codes['\o/'] 200 Some codes have multiple names, and both upper- and lower-case versions of the names are allowed. For example, ``codes.ok``, ``codes.OK``, and ``codes.okay`` all correspond to the HTTP status code 200. """ from .structures import LookupDict _codes = { # Informational. 100: ('continue',), 101: ('switching_protocols',), 102: ('processing',), 103: ('checkpoint',), 122: ('uri_too_long', 'request_uri_too_long'), 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'), 201: ('created',), 202: ('accepted',), 203: ('non_authoritative_info', 'non_authoritative_information'), 204: ('no_content',), 205: ('reset_content', 'reset'), 206: ('partial_content', 'partial'), 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'), 208: ('already_reported',), 226: ('im_used',), # Redirection. 300: ('multiple_choices',), 301: ('moved_permanently', 'moved', '\\o-'), 302: ('found',), 303: ('see_other', 'other'), 304: ('not_modified',), 305: ('use_proxy',), 306: ('switch_proxy',), 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 308: ('permanent_redirect', 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 # Client Error. 400: ('bad_request', 'bad'), 401: ('unauthorized',), 402: ('payment_required', 'payment'), 403: ('forbidden',), 404: ('not_found', '-o-'), 405: ('method_not_allowed', 'not_allowed'), 406: ('not_acceptable',), 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'), 408: ('request_timeout', 'timeout'), 409: ('conflict',), 410: ('gone',), 411: ('length_required',), 412: ('precondition_failed', 'precondition'), 413: ('request_entity_too_large',), 414: ('request_uri_too_large',), 415: ('unsupported_media_type', 'unsupported_media', 'media_type'), 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'), 417: ('expectation_failed',), 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'), 421: ('misdirected_request',), 422: ('unprocessable_entity', 'unprocessable'), 423: ('locked',), 424: ('failed_dependency', 'dependency'), 425: ('unordered_collection', 'unordered'), 426: ('upgrade_required', 'upgrade'), 428: ('precondition_required', 'precondition'), 429: ('too_many_requests', 'too_many'), 431: ('header_fields_too_large', 'fields_too_large'), 444: ('no_response', 'none'), 449: ('retry_with', 'retry'), 450: ('blocked_by_windows_parental_controls', 'parental_controls'), 451: ('unavailable_for_legal_reasons', 'legal_reasons'), 499: ('client_closed_request',), # Server Error. 500: ('internal_server_error', 'server_error', '/o\\', '✗'), 501: ('not_implemented',), 502: ('bad_gateway',), 503: ('service_unavailable', 'unavailable'), 504: ('gateway_timeout',), 505: ('http_version_not_supported', 'http_version'), 506: ('variant_also_negotiates',), 507: ('insufficient_storage',), 509: ('bandwidth_limit_exceeded', 'bandwidth'), 510: ('not_extended',), 511: ('network_authentication_required', 'network_auth', 'network_authentication'), } codes = LookupDict(name='status_codes') def _init(): for code, titles in _codes.items(): for title in titles: setattr(codes, title, code) if not title.startswith(('\\', '/')): setattr(codes, title.upper(), code) def doc(code): names = ', '.join('``%s``' % n for n in _codes[code]) return '* %d: %s' % (code, names) global __doc__ __doc__ = (__doc__ + '\n' + '\n'.join(doc(code) for code in sorted(_codes)) if __doc__ is not None else None) _init()
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/status_codes.py
status_codes.py
import os.path import socket from .urllib3.poolmanager import PoolManager, proxy_from_url from .urllib3.response import HTTPResponse from .urllib3.util import parse_url from .urllib3.util import Timeout as TimeoutSauce from .urllib3.util.retry import Retry from .urllib3.exceptions import ClosedPoolError from .urllib3.exceptions import ConnectTimeoutError from .urllib3.exceptions import HTTPError as _HTTPError from .urllib3.exceptions import InvalidHeader as _InvalidHeader from .urllib3.exceptions import MaxRetryError from .urllib3.exceptions import NewConnectionError from .urllib3.exceptions import ProxyError as _ProxyError from .urllib3.exceptions import ProtocolError from .urllib3.exceptions import ReadTimeoutError from .urllib3.exceptions import SSLError as _SSLError from .urllib3.exceptions import ResponseError from .urllib3.exceptions import LocationValueError from .models import Response from .compat import urlparse, basestring from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths, get_encoding_from_headers, prepend_scheme_if_needed, get_auth_from_url, urldefragauth, select_proxy) from .structures import CaseInsensitiveDict from .cookies import extract_cookies_to_jar from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError, ProxyError, RetryError, InvalidSchema, InvalidProxyURL, InvalidURL, InvalidHeader) from .auth import _basic_auth_str from .urllib3.contrib.socks import SOCKSProxyManager DEFAULT_POOLBLOCK = False DEFAULT_POOLSIZE = 10 DEFAULT_RETRIES = 0 DEFAULT_POOL_TIMEOUT = None class BaseAdapter(object): """The Base Transport Adapter""" def __init__(self): super(BaseAdapter, self).__init__() def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. """ raise NotImplementedError def close(self): """Cleans up adapter specific items.""" raise NotImplementedError class HTTPAdapter(BaseAdapter): """The built-in HTTP Adapter for urllib3. Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. This class will usually be created by the :class:`Session <Session>` class under the covers. :param pool_connections: The number of urllib3 connection pools to cache. :param pool_maxsize: The maximum number of connections to save in the pool. :param max_retries: The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed connections. If you need granular control over the conditions under which we retry a request, import urllib3's ``Retry`` class and pass that instead. :param pool_block: Whether the connection pool should block for connections. Usage:: >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) """ __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize', '_pool_block'] def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK): if max_retries == DEFAULT_RETRIES: self.max_retries = Retry(0, read=False) else: self.max_retries = Retry.from_int(max_retries) self.config = {} self.proxy_manager = {} super(HTTPAdapter, self).__init__() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize self._pool_block = pool_block self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) def __getstate__(self): return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): # Can't handle by adding 'proxy_manager' to self.__attrs__ because # self.poolmanager uses a lambda function, which isn't pickleable. self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager(self._pool_connections, self._pool_maxsize, block=self._pool_block) def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): """Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. """ # save these values for pickling self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs) def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith('socks'): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs) return manager def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify. """ if url.lower().startswith('https') and verify: cert_loc = None # Allow self-specified cert location. if verify is not True: cert_loc = verify if not cert_loc: cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) if not cert_loc or not os.path.exists(cert_loc): raise IOError("Could not find a suitable TLS CA certificate bundle, " "invalid path: {}".format(cert_loc)) conn.cert_reqs = 'CERT_REQUIRED' if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise IOError("Could not find the TLS certificate file, " "invalid path: {}".format(conn.cert_file)) if conn.key_file and not os.path.exists(conn.key_file): raise IOError("Could not find the TLS key file, " "invalid path: {}".format(conn.key_file)) def build_response(self, req, resp): """Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response """ response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, 'status', None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL("Please check proxy URL. It is malformed" " and could be missing the host.") proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear() def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and scheme != 'https') using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send(). """ pass def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) if username: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response """ try: conn = self.get_connection(request.url, proxies) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies) chunked = not ( request.body is None or 'Content-Length' in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError as e: # this may raise a string formatting error. err = ("Invalid timeout {}. Pass a (connect, read) " "timeout tuple, or a single float to set " "both timeouts to the same value".format(timeout)) raise ValueError(err) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout ) # Send the request. else: if hasattr(conn, 'proxy_pool'): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: skip_host = 'Host' in request.headers low_conn.putrequest(request.method, url, skip_accept_encoding=True, skip_host=skip_host) for header, value in request.headers.items(): low_conn.putheader(header, value) low_conn.endheaders() for i in request.body: low_conn.send(hex(len(i))[2:].encode('utf-8')) low_conn.send(b'\r\n') low_conn.send(i) low_conn.send(b'\r\n') low_conn.send(b'0\r\n\r\n') # Receive the response from the server try: # For Python 2.7, use buffering of HTTP responses r = low_conn.getresponse(buffering=True) except TypeError: # For compatibility with Python 3.3+ r = low_conn.getresponse() resp = HTTPResponse.from_httplib( r, pool=conn, connection=low_conn, preload_content=False, decode_content=False ) except: # If we hit any problems here, clean up the connection. # Then, reraise so that we can handle the actual exception. low_conn.close() raise except (ProtocolError, socket.error) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) elif isinstance(e, _InvalidHeader): raise InvalidHeader(e, request=request) else: raise return self.build_response(request, resp)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/adapters.py
adapters.py
import os import sys import time from datetime import timedelta from collections import OrderedDict from .auth import _basic_auth_str from .compat import cookielib, urljoin, urlparse, Mapping from .cookies import ( cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies) from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT from .hooks import default_hooks, dispatch_hook from ._internal_utils import to_native_string from .utils import to_key_val_list, default_headers, DEFAULT_PORTS from .exceptions import ( TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError) from .structures import CaseInsensitiveDict from .adapters import HTTPAdapter from .utils import ( requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies, get_auth_from_url, rewind_body, resolve_proxies ) from .status_codes import codes # formerly defined here, reexposed here for backward compatibility from .models import REDIRECT_STATI # Preferred clock, based on which one is more accurate on a given system. if sys.platform == 'win32': try: # Python 3.4+ preferred_clock = time.perf_counter except AttributeError: # Earlier than Python 3. preferred_clock = time.clock else: preferred_clock = time.time def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. none_keys = [k for (k, v) in merged_setting.items() if v is None] for key in none_keys: del merged_setting[key] return merged_setting def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class) class SessionRedirectMixin(object): def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. location = location.encode('latin1') return to_native_string(location, 'utf8') return None def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs): """Receives a Response. Returns a generator of Responses or Requests.""" hist = [] # keep track of history url = self.get_redirect_target(resp) previous_fragment = urlparse(req.url).fragment while url: prepared_request = req.copy() # Update history and keep track of redirects. # resp.history must ignore the original request in this loop hist.append(resp) resp.history = hist[1:] try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if len(resp.history) >= self.max_redirects: raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp) # Release the connection back into the pool. resp.close() # Handle redirection without scheme (see: RFC 1808 Section 4) if url.startswith('//'): parsed_rurl = urlparse(resp.url) url = ':'.join([to_native_string(parsed_rurl.scheme), url]) # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) parsed = urlparse(url) if parsed.fragment == '' and previous_fragment: parsed = parsed._replace(fragment=previous_fragment) elif parsed.fragment: previous_fragment = parsed.fragment url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # https://github.com/psf/requests/issues/1084 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): # https://github.com/psf/requests/issues/3490 purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding') for header in purged_headers: prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers headers.pop('Cookie', None) # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # A failed tell() sets `_body_position` to `object()`. This non-None # value ensures `rewindable` will be True, allowing us to raise an # UnrewindableBodyError, instead of hanging the connection. rewindable = ( prepared_request._body_position is not None and ('Content-Length' in headers or 'Transfer-Encoding' in headers) ) # Attempt to rewind consumed file-like object. if rewindable: rewind_body(prepared_request) # Override the original request. req = prepared_request if yield_requests: yield req else: resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) # extract redirect url, if any, for the next loop url = self.get_redirect_target(resp) yield resp def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if 'Authorization' in headers and self.should_strip_auth(response.request.url, url): # If we get redirected to a new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ headers = prepared_request.headers scheme = urlparse(prepared_request.url).scheme new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != 'HEAD': method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method class Session(SessionRedirectMixin): """A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage:: >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') <Response [200]> Or as a context manager:: >>> with requests.Session() as s: ... s.get('https://httpbin.org/get') <Response [200]> """ __attrs__ = [ 'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify', 'cert', 'adapters', 'stream', 'trust_env', 'max_redirects', ] def __init__(self): #: A case-insensitive dictionary of headers to be sent on each #: :class:`Request <Request>` sent from this #: :class:`Session <Session>`. self.headers = default_headers() #: Default Authentication tuple or object to attach to #: :class:`Request <Request>`. self.auth = None #: Dictionary mapping protocol or protocol and host to the URL of the proxy #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to #: be used on each :class:`Request <Request>`. self.proxies = {} #: Event-handling hooks. self.hooks = default_hooks() #: Dictionary of querystring data to attach to each #: :class:`Request <Request>`. The dictionary values may be lists for #: representing multivalued query parameters. self.params = {} #: Stream response content default. self.stream = False #: SSL Verification default. #: Defaults to `True`, requiring requests to verify the TLS certificate at the #: remote end. #: If verify is set to `False`, requests will accept any TLS certificate #: presented by the server, and will ignore hostname mismatches and/or #: expired certificates, which will make your application vulnerable to #: man-in-the-middle (MitM) attacks. #: Only set this to `False` for testing. self.verify = True #: SSL client certificate default, if String, path to ssl client #: cert file (.pem). If Tuple, ('cert', 'key') pair. self.cert = None #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default #: authentication and similar. self.trust_env = True #: A CookieJar containing all currently outstanding cookies set on this #: session. By default it is a #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but #: may be any other ``cookielib.CookieJar`` compatible object. self.cookies = cookiejar_from_dict({}) # Default connection adapters. self.adapters = OrderedDict() self.mount('https://', HTTPAdapter()) self.mount('http://', HTTPAdapter()) def __enter__(self): return self def __exit__(self, *args): self.close() def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When set to ``False``, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful during local development or testing. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs) def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs) def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs) def post(self, url, data=None, json=None, **kwargs): r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('POST', url, data=data, json=json, **kwargs) def put(self, url, data=None, **kwargs): r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PUT', url, data=data, **kwargs) def patch(self, url, data=None, **kwargs): r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PATCH', url, data=data, **kwargs) def delete(self, url, **kwargs): r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('DELETE', url, **kwargs) def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) if 'proxies' not in kwargs: kwargs['proxies'] = resolve_proxies( request, self.proxies, self.trust_env ) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Resolve redirects if allowed. if allow_redirects: # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) history = [resp for resp in gen] else: history = [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert} def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for {!r}".format(url)) def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close() def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key) def __getstate__(self): state = {attr: getattr(self, attr, None) for attr in self.__attrs__} return state def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def session(): """ Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session """ return Session()
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/sessions.py
sessions.py
import os import re import time import hashlib import threading import warnings from base64 import b64encode from .compat import urlparse, str, basestring from .cookies import extract_cookies_to_jar from ._internal_utils import to_native_string from .utils import parse_dict_header CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' CONTENT_TYPE_MULTI_PART = 'multipart/form-data' def _basic_auth_str(username, password): """Returns a Basic Auth string.""" # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backwards compatibility # for things like ints. This will be removed in 3.0.0. if not isinstance(username, basestring): warnings.warn( "Non-string usernames will no longer be supported in Requests " "3.0.0. Please convert the object you've passed in ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(username), category=DeprecationWarning, ) username = str(username) if not isinstance(password, basestring): warnings.warn( "Non-string passwords will no longer be supported in Requests " "3.0.0. Please convert the object you've passed in ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(type(password)), category=DeprecationWarning, ) password = str(password) # -- End Removal -- if isinstance(username, str): username = username.encode('latin1') if isinstance(password, str): password = password.encode('latin1') authstr = 'Basic ' + to_native_string( b64encode(b':'.join((username, password))).strip() ) return authstr class AuthBase(object): """Base class that all auth implementations derive from""" def __call__(self, r): raise NotImplementedError('Auth hooks must be callable.') class HTTPBasicAuth(AuthBase): """Attaches HTTP Basic Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password def __eq__(self, other): return all([ self.username == getattr(other, 'username', None), self.password == getattr(other, 'password', None) ]) def __ne__(self, other): return not self == other def __call__(self, r): r.headers['Authorization'] = _basic_auth_str(self.username, self.password) return r class HTTPProxyAuth(HTTPBasicAuth): """Attaches HTTP Proxy Authentication to a given Request object.""" def __call__(self, r): r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password) return r class HTTPDigestAuth(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password # Keep state in per-thread local storage self._thread_local = threading.local() def init_per_thread_state(self): # Ensure state is initialized just once per-thread if not hasattr(self._thread_local, 'init'): self._thread_local.init = True self._thread_local.last_nonce = '' self._thread_local.nonce_count = 0 self._thread_local.chal = {} self._thread_local.pos = None self._thread_local.num_401_calls = None def build_digest_header(self, method, url): """ :rtype: str """ realm = self._thread_local.chal['realm'] nonce = self._thread_local.chal['nonce'] qop = self._thread_local.chal.get('qop') algorithm = self._thread_local.chal.get('algorithm') opaque = self._thread_local.chal.get('opaque') hash_utf8 = None if algorithm is None: _algorithm = 'MD5' else: _algorithm = algorithm.upper() # lambdas assume digest modules are imported at the top level if _algorithm == 'MD5' or _algorithm == 'MD5-SESS': def md5_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.md5(x).hexdigest() hash_utf8 = md5_utf8 elif _algorithm == 'SHA': def sha_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha1(x).hexdigest() hash_utf8 = sha_utf8 elif _algorithm == 'SHA-256': def sha256_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha256(x).hexdigest() hash_utf8 = sha256_utf8 elif _algorithm == 'SHA-512': def sha512_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha512(x).hexdigest() hash_utf8 = sha512_utf8 KD = lambda s, d: hash_utf8("%s:%s" % (s, d)) if hash_utf8 is None: return None # XXX not implemented yet entdig = None p_parsed = urlparse(url) #: path is request-uri defined in RFC 2616 which should not be empty path = p_parsed.path or "/" if p_parsed.query: path += '?' + p_parsed.query A1 = '%s:%s:%s' % (self.username, realm, self.password) A2 = '%s:%s' % (method, path) HA1 = hash_utf8(A1) HA2 = hash_utf8(A2) if nonce == self._thread_local.last_nonce: self._thread_local.nonce_count += 1 else: self._thread_local.nonce_count = 1 ncvalue = '%08x' % self._thread_local.nonce_count s = str(self._thread_local.nonce_count).encode('utf-8') s += nonce.encode('utf-8') s += time.ctime().encode('utf-8') s += os.urandom(8) cnonce = (hashlib.sha1(s).hexdigest()[:16]) if _algorithm == 'MD5-SESS': HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce)) if not qop: respdig = KD(HA1, "%s:%s" % (nonce, HA2)) elif qop == 'auth' or 'auth' in qop.split(','): noncebit = "%s:%s:%s:%s:%s" % ( nonce, ncvalue, cnonce, 'auth', HA2 ) respdig = KD(HA1, noncebit) else: # XXX handle auth-int. return None self._thread_local.last_nonce = nonce # XXX should the partial digests be encoded too? base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ 'response="%s"' % (self.username, realm, nonce, path, respdig) if opaque: base += ', opaque="%s"' % opaque if algorithm: base += ', algorithm="%s"' % algorithm if entdig: base += ', digest="%s"' % entdig if qop: base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce) return 'Digest %s' % (base) def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self._thread_local.num_401_calls = 1 def handle_401(self, r, **kwargs): """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 if not 400 <= r.status_code < 500: self._thread_local.num_401_calls = 1 return r if self._thread_local.pos is not None: # Rewind the file position indicator of the body to where # it was to resend the request. r.request.body.seek(self._thread_local.pos) s_auth = r.headers.get('www-authenticate', '') if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2: self._thread_local.num_401_calls += 1 pat = re.compile(r'digest ', flags=re.IGNORECASE) self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1)) # Consume content and release the original connection # to allow our new request to reuse the same one. r.content r.close() prep = r.request.copy() extract_cookies_to_jar(prep._cookies, r.request, r.raw) prep.prepare_cookies(prep._cookies) prep.headers['Authorization'] = self.build_digest_header( prep.method, prep.url) _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r self._thread_local.num_401_calls = 1 return r def __call__(self, r): # Initialize per-thread state, if needed self.init_per_thread_state() # If we have a saved nonce, skip the 401 if self._thread_local.last_nonce: r.headers['Authorization'] = self.build_digest_header(r.method, r.url) try: self._thread_local.pos = r.body.tell() except AttributeError: # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # file position of the previous body. Ensure it's set to # None. self._thread_local.pos = None r.register_hook('response', self.handle_401) r.register_hook('response', self.handle_redirect) self._thread_local.num_401_calls = 1 return r def __eq__(self, other): return all([ self.username == getattr(other, 'username', None), self.password == getattr(other, 'password', None) ]) def __ne__(self, other): return not self == other
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/auth.py
auth.py
import random agents = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36 OPR/63.0.3368.43", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; LCTE; rv:11.0) like Gecko", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.54.16 (KHTML, like Gecko) Version/5.1.4 Safari/534.54.16", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3722.400 QQBrowser/10.5.3739.400", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 QIHU 360EE", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3947.100 Safari/537.36", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.111 Mobile Safari/537.36", "Mozilla/5.0 (Android 7.1.1; Mobile; rv:68.0) Gecko/68.0 Firefox/68.0", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk Build/NMF26F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Mobile Safari/537.36 OPR/53.0.2569.141117", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.90 Mobile Safari/537.36 EdgA/42.0.2.3819", "Mozilla/5.0 (Linux; U; Android 7.1.1; zh-cn; OPPO R9sk Build/NMF26F) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/9.6 Mobile Safari/537.36", "Mozilla/5.0 (Linux; U; Android 7.1.1; zh-cn; OPPO R9sk Build/NMF26F) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 OppoBrowser/10.5.1.2", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.97 Mobile Safari/537.36", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk Build/NMF26F) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 360 Alitephone Browser (1.5.0.90/1.0.100.1078) mso_sdk(1.0.0)", "Mozilla/5.0 (Linux; U; Android 7.1.1; zh-CN; OPPO R9sk Build/NMF26F) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.6.0.1040 Mobile Safari/537.36", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 LieBaoFast/5.12.3", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/48.0.2564.116 Mobile Safari/537.36 T7/9.1 baidubrowser/7.19.13.0 (Baidu; P1 7.1.1)", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.106 Mobile Safari/537.36 AWP/2.0 SogouMSE,SogouMobileBrowser/5.22.8", "Mozilla/5.0 (Linux; Android 7.1.1; OPPO R9sk Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 Mb2345Browser/11.0.1", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7", "Mozilla/5.0 (iPhone 6s; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0 MQQBrowser/8.3.0 Mobile/15B87 Safari/604.1 MttCustomUA/2 QBWebViewType/1 WKType/1", "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10", "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5", "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+", "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0", "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124", "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)", ] def random_user_agent(include_header=False): agent_str = random.choice(agents) if include_header: return "User-Agent", agent_str return agent_str
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/user_agent.py
user_agent.py
import codecs import contextlib import io import os import re import socket import struct import sys import tempfile import warnings import zipfile from collections import OrderedDict from .urllib3.util import make_headers from .urllib3.util import parse_url from . import certs # to_native_string is unused here, but imported here for backwards compatibility from ._internal_utils import to_native_string from .compat import parse_http_list as _parse_list_header from .compat import ( quote, urlparse, bytes, str, unquote, getproxies, proxy_bypass, urlunparse, basestring, integer_types, Mapping) from .cookies import cookiejar_from_dict from .structures import CaseInsensitiveDict from .exceptions import ( InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError) NETRC_FILES = ('.netrc', '_netrc') DEFAULT_CA_BUNDLE_PATH = certs.where() DEFAULT_PORTS = {'http': 80, 'https': 443} # Ensure that ', ' is used to preserve previous delimiter behavior. DEFAULT_ACCEPT_ENCODING = ", ".join( re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) ) if sys.platform == 'win32': # provide a proxy_bypass version on Windows without DNS lookups def proxy_bypass_registry(host): try: import winreg except ImportError: return False try: internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it proxyEnable = int(winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]) # ProxyOverride is almost always a string proxyOverride = winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0] except OSError: return False if not proxyEnable or not proxyOverride: return False # make a check value list from the registry entry: replace the # '<local>' string by the localhost entry and the corresponding # canonical entry. proxyOverride = proxyOverride.split(';') # now check if we match one of the registry values. for test in proxyOverride: if test == '<local>': if '.' not in host: return True test = test.replace(".", r"\.") # mask dots test = test.replace("*", r".*") # change glob sequence test = test.replace("?", r".") # change glob char if re.match(test, host, re.I): return True return False def proxy_bypass(host): # noqa """Return True, if the host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. """ return proxy_bypass_registry(host) def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" if hasattr(d, 'items'): d = d.items() return d def super_len(o): total_length = None current_position = 0 if hasattr(o, '__len__'): total_length = len(o) elif hasattr(o, 'len'): total_length = o.len elif hasattr(o, 'fileno'): try: fileno = o.fileno() except (io.UnsupportedOperation, AttributeError): # AttributeError is a surprising exception, seeing as how we've just checked # that `hasattr(o, 'fileno')`. It happens for objects obtained via # `Tarfile.extractfile()`, per issue 5229. pass else: total_length = os.fstat(fileno).st_size # Having used fstat to determine the file length, we need to # confirm that this file was opened up in binary mode. if 'b' not in o.mode: warnings.warn(( "Requests has determined the content-length for this " "request using the binary size of the file: however, the " "file has been opened in text mode (i.e. without the 'b' " "flag in the mode). This may lead to an incorrect " "content-length. In Requests 3.0, support will be removed " "for files in text mode."), FileModeWarning ) if hasattr(o, 'tell'): try: current_position = o.tell() except (OSError, IOError): # This can happen in some weird situations, such as when the file # is actually a special file descriptor like stdin. In this # instance, we don't know what the length is, so set it to zero and # let requests chunk it instead. if total_length is not None: current_position = total_length else: if hasattr(o, 'seek') and total_length is None: # StringIO and BytesIO have seek but no usable fileno try: # seek to end of file o.seek(0, 2) total_length = o.tell() # seek back to current position to support # partially read file-like objects o.seek(current_position or 0) except (OSError, IOError): total_length = 0 if total_length is None: total_length = 0 return max(0, total_length - current_position) def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" netrc_file = os.environ.get('NETRC') if netrc_file is not None: netrc_locations = (netrc_file,) else: netrc_locations = ('~/{}'.format(f) for f in NETRC_FILES) try: from netrc import netrc, NetrcParseError netrc_path = None for f in netrc_locations: try: loc = os.path.expanduser(f) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & # https://github.com/psf/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b':' if isinstance(url, str): splitstr = splitstr.decode('ascii') host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # App Engine hackiness. except (ImportError, AttributeError): pass def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name) def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) if not prefix: # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users break member = '/'.join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, member.split('/')[-1]) if not os.path.exists(extracted_path): # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition with atomic_open(extracted_path) as file_handler: file_handler.write(zip_file.read(member)) return extracted_path @contextlib.contextmanager def atomic_open(filename): """Write a file to the disk in an atomic fashion""" replacer = os.rename if sys.version_info[0] == 2 else os.replace tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) try: with os.fdopen(tmp_descriptor, 'wb') as tmp_handler: yield tmp_handler replacer(tmp_name, filename) except BaseException: os.remove(tmp_name) raise def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') return OrderedDict(value) def to_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(value, Mapping): value = value.items() return list(value) # From mitsuhiko/werkzeug (used with permission). def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result # From mitsuhiko/werkzeug (used with permission). def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict """ result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result # From mitsuhiko/werkzeug (used with permission). def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != '\\\\': return value.replace('\\\\', '\\').replace('\\"', '"') return value def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar """ return cookiejar_from_dict(cookie_dict, cj) def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ warnings.warn(( 'In requests 3.0, get_encodings_from_content will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) pragma_re = re.compile( r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I) xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') return (charset_re.findall(content) + pragma_re.findall(content) + xml_re.findall(content)) def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1:].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = headers.get('content-type') if not content_type: return None content_type, params = _parse_content_type_header(content_type) if 'charset' in params: return params['charset'].strip("'\"") if 'text' in content_type: return 'ISO-8859-1' if 'application/json' in content_type: # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset return 'utf-8' def stream_decode_response_unicode(iterator, r): """Stream decodes a iterator.""" if r.encoding is None: for item in iterator: yield item return decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace') for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode(b'', final=True) if rv: yield rv def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content # The unreserved URI characters (RFC 3986) UNRESERVED_SET = frozenset( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~") def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str """ parts = uri.split('%') for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 and h.isalnum(): try: c = chr(int(h, 16)) except ValueError: raise InvalidURL("Invalid percent-escape sequence: '%s'" % h) if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = '%' + parts[i] else: parts[i] = '%' + parts[i] return ''.join(parts) def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent) def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') netmask = struct.unpack( '=L', socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask) def dotted_netmask(mask): """Converts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str """ bits = 0xffffffff ^ (1 << 32 - mask) - 1 return socket.inet_ntoa(struct.pack('>I', bits)) def is_ipv4_address(string_ip): """ :rtype: bool """ try: socket.inet_aton(string_ip) except socket.error: return False return True def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split('/')[0]) except socket.error: return False else: return False return True @contextlib.contextmanager def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). def get_proxy(k): return os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy('no_proxy') parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = ( host for host in no_proxy.replace(' ', '').split(',') if host ) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += ':{}'.format(parsed.port) for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ('no_proxy', no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False def get_environ_proxies(url, no_proxy=None): """ Return a dict of environment proxies. :rtype: dict """ if should_bypass_proxies(url, no_proxy=no_proxy): return {} else: return getproxies() def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get('all')) proxy_keys = [ urlparts.scheme + '://' + urlparts.hostname, urlparts.scheme, 'all://' + urlparts.hostname, 'all', ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy def resolve_proxies(request, proxies, trust_env=True): """This method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such a NO_PROXY to strip proxy configurations. :param request: Request or PreparedRequest :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs :param trust_env: Boolean declaring whether to trust environment configs :rtype: dict """ proxies = proxies if proxies is not None else {} url = request.url scheme = urlparse(url).scheme no_proxy = proxies.get('no_proxy') new_proxies = proxies.copy() if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) return new_proxies def default_user_agent(name="zdppy-requests"): """ Return a string representing the default user agent. :rtype: str """ return '%s/%s' % (name, "0.1.0") def default_headers(): """ :rtype: requests.structures.CaseInsensitiveDict """ return CaseInsensitiveDict({ 'User-Agent': default_user_agent(), 'Accept-Encoding': DEFAULT_ACCEPT_ENCODING, 'Accept': '*/*', 'Connection': 'keep-alive', }) def parse_header_links(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = ' \'"' value = value.strip(replace_chars) if not value: return links for val in re.split(', *<', value): try: url, params = val.split(';', 1) except ValueError: url, params = val, '' link = {'url': url.strip('<> \'"')} for param in params.split(';'): try: key, value = param.split('=') except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links # Null bytes; no need to recreate these on each call to guess_json_utf _null = '\x00'.encode('ascii') # encoding to ASCII for Python 3 _null2 = _null * 2 _null3 = _null * 3 def guess_json_utf(data): """ :rtype: str """ # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. sample = data[:4] if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): return 'utf-32' # BOM included if sample[:3] == codecs.BOM_UTF8: return 'utf-8-sig' # BOM included, MS style (discouraged) if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): return 'utf-16' # BOM included nullcount = sample.count(_null) if nullcount == 0: return 'utf-8' if nullcount == 2: if sample[::2] == _null2: # 1st and 3rd are null return 'utf-16-be' if sample[1::2] == _null2: # 2nd and 4th are null return 'utf-16-le' # Did not detect 2 valid UTF-16 ascii-range characters if nullcount == 3: if sample[:3] == _null3: return 'utf-32-be' if sample[1:] == _null3: return 'utf-32-le' # Did not detect a valid UTF-32 ascii-range character return None def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ parsed = parse_url(url) scheme, auth, host, port, path, query, fragment = parsed # A defect in urlparse determines that there isn't a netloc present in some # urls. We previously assumed parsing was overly cautious, and swapped the # netloc and path. Due to a lack of tests on the original defect, this is # maintained with parse_url for backwards compatibility. netloc = parsed.netloc if not netloc: netloc, path = path, netloc if auth: # parse_url doesn't provide the netloc with auth # so we'll add it ourselves. netloc = '@'.join([auth, netloc]) if scheme is None: scheme = new_scheme if path is None: path = '' return urlunparse((scheme, netloc, path, '', query, fragment)) def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth # Moved outside of function to avoid recompile every call _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$') _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$') def check_header_validity(header): """Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). """ name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader( "Invalid return character or leading space in header: %s" % name) except TypeError: raise InvalidHeader("Value for header {%s: %s} must be of type str or " "bytes, not %s" % (name, value, type(value))) def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, path, params, query, '')) def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, 'seek', None) if body_seek is not None and isinstance(prepared_request._body_position, integer_types): try: body_seek(prepared_request._body_position) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect.") else: raise UnrewindableBodyError( "Unable to rewind request body for redirect.")
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/utils.py
utils.py
import copy import time import calendar from ._internal_utils import to_native_string from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping try: import threading except ImportError: import dummy_threading as threading class MockRequest(object): """Wraps a `requests.Request` to mimic a `urllib2.Request`. The code in `cookielib.CookieJar` expects this interface in order to correctly manage cookie policies, i.e., determine whether a cookie can be set, given the domains of the request and the cookie. The original request object is read-only. The client is responsible for collecting the new headers via `get_new_headers()` and interpreting them appropriately. You probably want `get_cookie_header`, defined below. """ def __init__(self, request): self._r = request self._new_headers = {} self.type = urlparse(self._r.url).scheme def get_type(self): return self.type def get_host(self): return urlparse(self._r.url).netloc def get_origin_req_host(self): return self.get_host() def get_full_url(self): # Only return the response's URL if the user hadn't set the Host # header if not self._r.headers.get('Host'): return self._r.url # If they did set it, retrieve it and reconstruct the expected domain host = to_native_string(self._r.headers['Host'], encoding='utf-8') parsed = urlparse(self._r.url) # Reconstruct the URL as we expect it return urlunparse([ parsed.scheme, host, parsed.path, parsed.params, parsed.query, parsed.fragment ]) def is_unverifiable(self): return True def has_header(self, name): return name in self._r.headers or name in self._new_headers def get_header(self, name, default=None): return self._r.headers.get(name, self._new_headers.get(name, default)) def add_header(self, key, val): """cookielib has no legitimate use for this method; add it back if you find one.""" raise NotImplementedError("Cookie headers should be added with add_unredirected_header()") def add_unredirected_header(self, name, value): self._new_headers[name] = value def get_new_headers(self): return self._new_headers @property def unverifiable(self): return self.is_unverifiable() @property def origin_req_host(self): return self.get_origin_req_host() @property def host(self): return self.get_host() class MockResponse(object): """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. ...what? Basically, expose the parsed HTTP headers from the server response the way `cookielib` expects to see them. """ def __init__(self, headers): """Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers """ self._headers = headers def info(self): return self._headers def getheaders(self, name): self._headers.getheaders(name) def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object """ if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req) def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie') def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name) class CookieConflictError(RuntimeError): """There are two cookies that meet the criteria specified in the cookie jar. Use .get and .set and include domain and path args in order to be more specific. """ class RequestsCookieJar(cookielib.CookieJar, MutableMapping): """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Requests does not use the dict interface internally; it's just for compatibility with external client code. All requests code should work out of the box with externally provided instances of ``CookieJar``, e.g. ``LWPCookieJar`` and ``FileCookieJar``. Unlike a regular CookieJar, this class is pickleable. .. warning:: dictionary operations that are normally O(1) may be O(n). """ def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). """ try: return self._find_no_duplicates(name, domain, path) except KeyError: return default def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. """ # support client code that unsets cookies by assignment of a None value: if value is None: remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c def iterkeys(self): """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems(). """ for cookie in iter(self): yield cookie.name def keys(self): """Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items(). """ return list(self.iterkeys()) def itervalues(self): """Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems(). """ for cookie in iter(self): yield cookie.value def values(self): """Dict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items(). """ return list(self.itervalues()) def iteritems(self): """Dict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues(). """ for cookie in iter(self): yield cookie.name, cookie.value def items(self): """Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values(). """ return list(self.iteritems()) def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: return True domains.append(cookie.domain) return False # there is only one domain in jar def get_dict(self, domain=None, path=None): """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. :rtype: dict """ dictionary = {} for cookie in iter(self): if ( (domain is None or cookie.domain == domain) and (path is None or cookie.path == path) ): dictionary[cookie.name] = cookie.value return dictionary def __contains__(self, name): try: return super(RequestsCookieJar, self).__contains__(name) except CookieConflictError: return True def __getitem__(self, name): """Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1). """ return self._find_no_duplicates(name) def __setitem__(self, name, value): """Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead. """ self.set(name, value) def __delitem__(self, name): """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s ``remove_cookie_by_name()``. """ remove_cookie_by_name(self, name) def set_cookie(self, cookie, *args, **kwargs): if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'): cookie.value = cookie.value.replace('\\"', '') return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs) def update(self, other): """Updates this jar with cookies from another CookieJar or dict-like""" if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else: super(RequestsCookieJar, self).update(other) def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ toReturn = None for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError('There are multiple cookies with name, %r' % (name)) toReturn = cookie.value # we will eventually return this as long as no cookie conflict if toReturn: return toReturn raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def __getstate__(self): """Unlike a normal CookieJar, this class is pickleable.""" state = self.__dict__.copy() # remove the unpickleable RLock object state.pop('_cookies_lock') return state def __setstate__(self, state): """Unlike a normal CookieJar, this class is pickleable.""" self.__dict__.update(state) if '_cookies_lock' not in self.__dict__: self._cookies_lock = threading.RLock() def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj def get_policy(self): """Return the CookiePolicy instance used.""" return self._policy def _copy_cookie_jar(jar): if jar is None: return None if hasattr(jar, 'copy'): # We're dealing with an instance of RequestsCookieJar return jar.copy() # We're dealing with a generic CookieJar instance new_jar = copy.copy(jar) new_jar.clear() for cookie in jar: new_jar.set_cookie(copy.copy(cookie)) return new_jar def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rest': {'HttpOnly': None}, 'rfc2109': False, } badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result) def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: try: expires = int(time.time() + int(morsel['max-age'])) except ValueError: raise TypeError('max-age: %s must be integer' % morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm( time.strptime(morsel['expires'], time_template) ) return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, ) def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. :rtype: CookieJar """ if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar def merge_cookies(cookiejar, cookies): """Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar """ if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError('You can only merge into CookieJar') if isinstance(cookies, dict): cookiejar = cookiejar_from_dict( cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/cookies.py
cookies.py
from . import sessions def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') >>> req <Response [200]> """ # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs) def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('get', url, params=params, **kwargs) def options(url, **kwargs): r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('options', url, **kwargs) def head(url, **kwargs): r"""Sends a HEAD request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. If `allow_redirects` is not provided, it will be set to `False` (as opposed to the default :meth:`request` behavior). :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return request('head', url, **kwargs) def post(url, data=None, json=None, **kwargs): r"""Sends a POST request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('post', url, data=data, json=json, **kwargs) def put(url, data=None, **kwargs): r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('put', url, data=data, **kwargs) def patch(url, data=None, **kwargs): r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('patch', url, data=data, **kwargs) def delete(url, **kwargs): r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('delete', url, **kwargs)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/api.py
api.py
from collections import OrderedDict from .compat import Mapping, MutableMapping class CaseInsensitiveDict(MutableMapping): """A case-insensitive ``dict``-like object. Implements all methods and operations of ``MutableMapping`` as well as dict's ``copy``. Also provides ``lower_items``. All keys are expected to be strings. The structure remembers the case of the last key to be set, and ``iter(instance)``, ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` will contain case-sensitive keys. However, querying and contains testing is case insensitive:: cid = CaseInsensitiveDict() cid['Accept'] = 'application/json' cid['aCCEPT'] == 'application/json' # True list(cid) == ['Accept'] # True For example, ``headers['content-encoding']`` will return the value of a ``'Content-Encoding'`` response header, regardless of how the header name was originally stored. If the constructor, ``.update``, or equality comparison operations are given keys that have equal ``.lower()``s, the behavior is undefined. """ def __init__(self, data=None, **kwargs): self._store = OrderedDict() if data is None: data = {} self.update(data, **kwargs) def __setitem__(self, key, value): # Use the lowercased key for lookups, but store the actual # key alongside the value. self._store[key.lower()] = (key, value) def __getitem__(self, key): return self._store[key.lower()][1] def __delitem__(self, key): del self._store[key.lower()] def __iter__(self): return (casedkey for casedkey, mappedvalue in self._store.values()) def __len__(self): return len(self._store) def lower_items(self): """Like iteritems(), but with all lowercase keys.""" return ( (lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items() ) def __eq__(self, other): if isinstance(other, Mapping): other = CaseInsensitiveDict(other) else: return NotImplemented # Compare insensitively return dict(self.lower_items()) == dict(other.lower_items()) # Copy is required def copy(self): return CaseInsensitiveDict(self._store.values()) def __repr__(self): return str(dict(self.items())) class LookupDict(dict): """Dictionary lookup object.""" def __init__(self, name=None): self.name = name super(LookupDict, self).__init__() def __repr__(self): return '<lookup \'%s\'>' % (self.name) def __getitem__(self, key): # We allow fall-through here, so values default to None return self.__dict__.get(key, None) def get(self, key, default=None): return self.__dict__.get(key, default)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/structures.py
structures.py
from __future__ import print_function import json import platform import sys import ssl from . import idna from . import urllib3 from . import __version__ as requests_version import charset_normalizer chardet = None from .urllib3.contrib import pyopenssl def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == 'CPython': implementation_version = platform.python_version() elif implementation == 'PyPy': implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': implementation_version = ''.join([ implementation_version, sys.pypy_version_info.releaselevel ]) elif implementation == 'Jython': implementation_version = platform.python_version() # Complete Guess elif implementation == 'IronPython': implementation_version = platform.python_version() # Complete Guess else: implementation_version = 'Unknown' return {'name': implementation, 'version': implementation_version} def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } implementation_info = _implementation() urllib3_info = {'version': urllib3.__version__} charset_normalizer_info = {'version': None} chardet_info = {'version': None} if charset_normalizer: charset_normalizer_info = {'version': charset_normalizer.__version__} if chardet: chardet_info = {'version': chardet.__version__} pyopenssl_info = { 'version': None, 'openssl_version': '', } if OpenSSL: pyopenssl_info = { 'version': OpenSSL.__version__, 'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER, } cryptography_info = { 'version': getattr(cryptography, '__version__', ''), } idna_info = { 'version': getattr(idna, '__version__', ''), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = { 'version': '%x' % system_ssl if system_ssl is not None else '' } return { 'platform': platform_info, 'implementation': implementation_info, 'system_ssl': system_ssl_info, 'using_pyopenssl': pyopenssl is not None, 'using_charset_normalizer': chardet is None, 'pyOpenSSL': pyopenssl_info, 'urllib3': urllib3_info, 'chardet': chardet_info, 'charset_normalizer': charset_normalizer_info, 'cryptography': cryptography_info, 'idna': idna_info, 'requests': { 'version': requests_version, }, } def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2)) if __name__ == '__main__': main()
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/help.py
help.py
import datetime import sys import encodings.idna from .urllib3.fields import RequestField from .urllib3.filepost import encode_multipart_formdata from .urllib3.util import parse_url from .urllib3.exceptions import ( DecodeError, ReadTimeoutError, ProtocolError, LocationParseError) from io import UnsupportedOperation from .hooks import default_hooks from .structures import CaseInsensitiveDict from .auth import HTTPBasicAuth from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar from .exceptions import ( HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError, ContentDecodingError, ConnectionError, StreamConsumedError, InvalidJSONError) from .exceptions import JSONDecodeError as RequestsJSONDecodeError from ._internal_utils import to_native_string, unicode_is_ascii from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, iter_slices, guess_json_utf, super_len, check_header_validity) from .compat import ( Callable, Mapping, cookielib, urlunparse, urlsplit, urlencode, str, bytes, chardet, builtin_str, basestring, JSONDecodeError) from .compat import json as complexjson from .status_codes import codes #: The set of HTTP status codes that indicate an automatically #: processable redirect. REDIRECT_STATI = ( codes.moved, # 301 codes.found, # 302 codes.other, # 303 codes.temporary_redirect, # 307 codes.permanent_redirect, # 308 ) DEFAULT_REDIRECT_LIMIT = 30 CONTENT_CHUNK_SIZE = 10 * 1024 ITER_CHUNK_SIZE = 512 class RequestEncodingMixin(object): @property def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url) @staticmethod 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 @staticmethod def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). """ if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, '__iter__'): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( (field.decode('utf-8') if isinstance(field, bytes) else field, v.encode('utf-8') if isinstance(v, str) else v)) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp elif hasattr(fp, 'read'): fdata = fp.read() elif fp is None: continue else: fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type class RequestHooksMixin(object): def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError( 'Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend( h for h in hook if isinstance(h, Callable)) def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False class Request(RequestHooksMixin): """A user-created :class:`Request <Request>` object. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param json: json for the body to attach to the request (if files or data is not specified). :param params: URL parameters to append to the URL. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> """ def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies def __repr__(self): return '<Request [%s]>' % (self.method) def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Instances are generated from a :class:`Request <Request>` object, and should not be instantiated manually; doing so may produce undesirable effects. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() >>> r <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]> """ def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() #: integer denoting starting position of a readable file-like body. self._body_position = None def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def __repr__(self): return '<PreparedRequest [%s]>' % (self.method) def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks p._body_position = self._body_position return p def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = to_native_string(self.method.upper()) @staticmethod 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 def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/psf/requests/pull/2238 if isinstance(url, bytes): url = url.decode('utf8') else: url = str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: error = ( "Invalid URL {0!r}: No scheme supplied. Perhaps you meant http://{0}?") error = error.format(to_native_string(url, 'utf8')) raise MissingSchema(error) if not host: raise InvalidURL("Invalid URL %r: No host supplied" % url) # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL('URL has an invalid label.') elif host.startswith((u'*', u'.')): raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse( [scheme, netloc, path, None, query, fragment])) self.url = url def prepare_headers(self, headers): """Prepares the given HTTP headers.""" self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): # Raise exception on invalid header value. check_header_validity(header) name, value = header self.headers[to_native_string(name)] = value def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = 'application/json' try: body = complexjson.dumps(json, allow_nan=False) except ValueError as ve: raise InvalidJSONError(ve, request=self) if not isinstance(body, bytes): body = body.encode('utf-8') is_stream = all([ hasattr(data, '__iter__'), not isinstance(data, (basestring, list, tuple, Mapping)) ]) if is_stream: try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None body = data if getattr(body, 'tell', None) is not None: # Record the current file position before reading. # This will allow us to rewind a file in the event # of a redirect. try: self._body_position = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body self._body_position = object() if files: raise NotImplementedError( 'Streamed bodies and files are mutually exclusive.') if length: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, 'read'): content_type = None else: content_type = 'application/x-www-form-urlencoded' self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ('content-type' not in self.headers): self.headers['Content-Type'] = content_type self.body = body def prepare_content_length(self, body): """Prepare Content-Length header based on request method and body""" if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked. self.headers['Content-Length'] = builtin_str(length) elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None: # Set Content-Length to 0 for methods that can have a body # but don't provide one. (i.e. not GET or HEAD) self.headers['Content-Length'] = '0' def prepare_auth(self, auth, url=''): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body) def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand. """ if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers['Cookie'] = cookie_header def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: self.register_hook(event, hooks[event]) class Response(object): """The :class:`Response <Response>` object, which contains a server's response to an HTTP request. """ __attrs__ = [ '_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request' ] def __init__(self): self._content = False self._content_consumed = False self._next = None #: Integer Code of responded HTTP Status, e.g. 404 or 200. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. #: This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta). #: This property specifically measures the time taken between sending #: the first byte of the request and finishing parsing the headers. It #: is therefore unaffected by consuming the response content or the #: value of the ``stream`` keyword argument. self.elapsed = datetime.timedelta(0) #: The :class:`PreparedRequest <PreparedRequest>` object to which this #: is a response. self.request = None def __enter__(self): return self def __exit__(self, *args): self.close() def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, '_content_consumed', True) setattr(self, 'raw', None) def __repr__(self): return '<Response [%s]>' % (self.status_code) def __bool__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __nonzero__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128) @property def ok(self): """Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ try: self.raise_for_status() except HTTPError: return False return True @property def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """ return ('location' in self.headers and self.status_code in REDIRECT_STATI) @property def is_permanent_redirect(self): """True if this Response one of the permanent versions of redirect.""" return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)) @property def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next @property def apparent_encoding(self): """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" return chardet.detect(self.content)['encoding'] def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): # Special case for urllib3. if hasattr(self.raw, 'stream'): try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) else: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance(chunk_size, int): raise TypeError( "chunk_size must be an int, it is instead a %s." % type(chunk_size)) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. """ pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending @property def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. if self._content_consumed: raise RuntimeError( 'The content for this response was already consumed') if self.status_code == 0 or self.raw is None: self._content = None else: self._content = b''.join( self.iter_content(CONTENT_CHUNK_SIZE)) or b'' self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content @property def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``charset_normalizer`` or ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return str('') # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors='replace') return content def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises requests.exceptions.JSONDecodeError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using charset_normalizer to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads( self.content.decode(encoding), **kwargs ) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass try: return complexjson.loads(self.text, **kwargs) except JSONDecodeError as e: # Catch JSON-related errors and raise as requests.JSONDecodeError # This aliases json.JSONDecodeError and simplejson.JSONDecodeError if is_py2: # e is a ValueError raise RequestsJSONDecodeError(e.message) else: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) @property def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') l[key] = link return l def raise_for_status(self): """Raises :class:`HTTPError`, if one occurred.""" http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. (See PR #3538) try: reason = self.reason.decode('utf-8') except UnicodeDecodeError: reason = self.reason.decode('iso-8859-1') else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = u'%s Client Error: %s for url: %s' % ( self.status_code, reason, self.url) elif 500 <= self.status_code < 600: http_error_msg = u'%s Server Error: %s for url: %s' % ( self.status_code, reason, self.url) if http_error_msg: raise HTTPError(http_error_msg, response=self) def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, 'release_conn', None) if release_conn is not None: release_conn()
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/models.py
models.py
from .compat import JSONDecodeError as CompatJSONDecodeError from .urllib3.exceptions import HTTPError as BaseHTTPError class RequestException(IOError): """There was an ambiguous exception that occurred while handling your request. """ def __init__(self, *args, **kwargs): """Initialize RequestException with `request` and `response` objects.""" response = kwargs.pop('response', None) self.response = response self.request = kwargs.pop('request', None) if (response is not None and not self.request and hasattr(response, 'request')): self.request = self.response.request super(RequestException, self).__init__(*args, **kwargs) class InvalidJSONError(RequestException): """A JSON error occurred.""" class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): """Couldn't decode the text into json""" class HTTPError(RequestException): """An HTTP error occurred.""" class ConnectionError(RequestException): """A Connection error occurred.""" class ProxyError(ConnectionError): """A proxy error occurred.""" class SSLError(ConnectionError): """An SSL error occurred.""" class Timeout(RequestException): """The request timed out. Catching this error will catch both :exc:`~requests.exceptions.ConnectTimeout` and :exc:`~requests.exceptions.ReadTimeout` errors. """ class ConnectTimeout(ConnectionError, Timeout): """The request timed out while trying to connect to the remote server. Requests that produced this error are safe to retry. """ class ReadTimeout(Timeout): """The server did not send any data in the allotted amount of time.""" class URLRequired(RequestException): """A valid URL is required to make a request.""" class TooManyRedirects(RequestException): """Too many redirects.""" class MissingSchema(RequestException, ValueError): """The URL scheme (e.g. http or https) is missing.""" class InvalidSchema(RequestException, ValueError): """The URL scheme provided is either invalid or unsupported.""" class InvalidURL(RequestException, ValueError): """The URL provided was somehow invalid.""" class InvalidHeader(RequestException, ValueError): """The header value provided was somehow invalid.""" class InvalidProxyURL(InvalidURL): """The proxy URL provided is invalid.""" class ChunkedEncodingError(RequestException): """The server declared chunked encoding but sent an invalid chunk.""" class ContentDecodingError(RequestException, BaseHTTPError): """Failed to decode response content.""" class StreamConsumedError(RequestException, TypeError): """The content for this response was already consumed.""" class RetryError(RequestException): """Custom retries logic failed""" class UnrewindableBodyError(RequestException): """Requests encountered an error when trying to rewind a body.""" # Warnings class RequestsWarning(Warning): """Base warning for Requests.""" class FileModeWarning(RequestsWarning, DeprecationWarning): """A file was opened in text mode, but Requests determined its binary length.""" class RequestsDependencyWarning(RequestsWarning): """An imported dependency doesn't match the expected version range."""
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/exceptions.py
exceptions.py
from .core import encode, decode, alabel, ulabel, IDNAError import codecs import re from typing import Tuple, Optional _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]') class Codec(codecs.Codec): def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]: if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return b"", 0 return encode(data), len(data) def decode(self, data: bytes, errors: str = 'strict') -> Tuple[str, int]: if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return '', 0 return decode(data), len(data) class IncrementalEncoder(codecs.BufferedIncrementalEncoder): def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return "", 0 labels = _unicode_dots_re.split(data) trailing_dot = '' if labels: if not labels[-1]: trailing_dot = '.' del labels[-1] elif not final: # Keep potentially unfinished label until the next call del labels[-1] if labels: trailing_dot = '.' result = [] size = 0 for label in labels: result.append(alabel(label)) if size: size += 1 size += len(label) # Join with U+002E result_str = '.'.join(result) + trailing_dot # type: ignore size += len(trailing_dot) return result_str, size class IncrementalDecoder(codecs.BufferedIncrementalDecoder): def _buffer_decode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return ('', 0) labels = _unicode_dots_re.split(data) trailing_dot = '' if labels: if not labels[-1]: trailing_dot = '.' del labels[-1] elif not final: # Keep potentially unfinished label until the next call del labels[-1] if labels: trailing_dot = '.' result = [] size = 0 for label in labels: result.append(ulabel(label)) if size: size += 1 size += len(label) result_str = '.'.join(result) + trailing_dot size += len(trailing_dot) return (result_str, size) class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass def getregentry() -> codecs.CodecInfo: # Compatibility as a search_function for codecs.register() return codecs.CodecInfo( name='idna', encode=Codec().encode, # type: ignore decode=Codec().decode, # type: ignore incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamwriter=StreamWriter, streamreader=StreamReader, )
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/idna/codec.py
codec.py
from typing import List, Tuple, Union """IDNA Mapping Table from UTS46.""" __version__ = '14.0.0' def _seg_0() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x0, '3'), (0x1, '3'), (0x2, '3'), (0x3, '3'), (0x4, '3'), (0x5, '3'), (0x6, '3'), (0x7, '3'), (0x8, '3'), (0x9, '3'), (0xA, '3'), (0xB, '3'), (0xC, '3'), (0xD, '3'), (0xE, '3'), (0xF, '3'), (0x10, '3'), (0x11, '3'), (0x12, '3'), (0x13, '3'), (0x14, '3'), (0x15, '3'), (0x16, '3'), (0x17, '3'), (0x18, '3'), (0x19, '3'), (0x1A, '3'), (0x1B, '3'), (0x1C, '3'), (0x1D, '3'), (0x1E, '3'), (0x1F, '3'), (0x20, '3'), (0x21, '3'), (0x22, '3'), (0x23, '3'), (0x24, '3'), (0x25, '3'), (0x26, '3'), (0x27, '3'), (0x28, '3'), (0x29, '3'), (0x2A, '3'), (0x2B, '3'), (0x2C, '3'), (0x2D, 'V'), (0x2E, 'V'), (0x2F, '3'), (0x30, 'V'), (0x31, 'V'), (0x32, 'V'), (0x33, 'V'), (0x34, 'V'), (0x35, 'V'), (0x36, 'V'), (0x37, 'V'), (0x38, 'V'), (0x39, 'V'), (0x3A, '3'), (0x3B, '3'), (0x3C, '3'), (0x3D, '3'), (0x3E, '3'), (0x3F, '3'), (0x40, '3'), (0x41, 'M', 'a'), (0x42, 'M', 'b'), (0x43, 'M', 'c'), (0x44, 'M', 'd'), (0x45, 'M', 'e'), (0x46, 'M', 'f'), (0x47, 'M', 'g'), (0x48, 'M', 'h'), (0x49, 'M', 'i'), (0x4A, 'M', 'j'), (0x4B, 'M', 'k'), (0x4C, 'M', 'l'), (0x4D, 'M', 'm'), (0x4E, 'M', 'n'), (0x4F, 'M', 'o'), (0x50, 'M', 'p'), (0x51, 'M', 'q'), (0x52, 'M', 'r'), (0x53, 'M', 's'), (0x54, 'M', 't'), (0x55, 'M', 'u'), (0x56, 'M', 'v'), (0x57, 'M', 'w'), (0x58, 'M', 'x'), (0x59, 'M', 'y'), (0x5A, 'M', 'z'), (0x5B, '3'), (0x5C, '3'), (0x5D, '3'), (0x5E, '3'), (0x5F, '3'), (0x60, '3'), (0x61, 'V'), (0x62, 'V'), (0x63, 'V'), ] def _seg_1() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x64, 'V'), (0x65, 'V'), (0x66, 'V'), (0x67, 'V'), (0x68, 'V'), (0x69, 'V'), (0x6A, 'V'), (0x6B, 'V'), (0x6C, 'V'), (0x6D, 'V'), (0x6E, 'V'), (0x6F, 'V'), (0x70, 'V'), (0x71, 'V'), (0x72, 'V'), (0x73, 'V'), (0x74, 'V'), (0x75, 'V'), (0x76, 'V'), (0x77, 'V'), (0x78, 'V'), (0x79, 'V'), (0x7A, 'V'), (0x7B, '3'), (0x7C, '3'), (0x7D, '3'), (0x7E, '3'), (0x7F, '3'), (0x80, 'X'), (0x81, 'X'), (0x82, 'X'), (0x83, 'X'), (0x84, 'X'), (0x85, 'X'), (0x86, 'X'), (0x87, 'X'), (0x88, 'X'), (0x89, 'X'), (0x8A, 'X'), (0x8B, 'X'), (0x8C, 'X'), (0x8D, 'X'), (0x8E, 'X'), (0x8F, 'X'), (0x90, 'X'), (0x91, 'X'), (0x92, 'X'), (0x93, 'X'), (0x94, 'X'), (0x95, 'X'), (0x96, 'X'), (0x97, 'X'), (0x98, 'X'), (0x99, 'X'), (0x9A, 'X'), (0x9B, 'X'), (0x9C, 'X'), (0x9D, 'X'), (0x9E, 'X'), (0x9F, 'X'), (0xA0, '3', ' '), (0xA1, 'V'), (0xA2, 'V'), (0xA3, 'V'), (0xA4, 'V'), (0xA5, 'V'), (0xA6, 'V'), (0xA7, 'V'), (0xA8, '3', ' ̈'), (0xA9, 'V'), (0xAA, 'M', 'a'), (0xAB, 'V'), (0xAC, 'V'), (0xAD, 'I'), (0xAE, 'V'), (0xAF, '3', ' ̄'), (0xB0, 'V'), (0xB1, 'V'), (0xB2, 'M', '2'), (0xB3, 'M', '3'), (0xB4, '3', ' ́'), (0xB5, 'M', 'μ'), (0xB6, 'V'), (0xB7, 'V'), (0xB8, '3', ' ̧'), (0xB9, 'M', '1'), (0xBA, 'M', 'o'), (0xBB, 'V'), (0xBC, 'M', '1⁄4'), (0xBD, 'M', '1⁄2'), (0xBE, 'M', '3⁄4'), (0xBF, 'V'), (0xC0, 'M', 'à'), (0xC1, 'M', 'á'), (0xC2, 'M', 'â'), (0xC3, 'M', 'ã'), (0xC4, 'M', 'ä'), (0xC5, 'M', 'å'), (0xC6, 'M', 'æ'), (0xC7, 'M', 'ç'), ] def _seg_2() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xC8, 'M', 'è'), (0xC9, 'M', 'é'), (0xCA, 'M', 'ê'), (0xCB, 'M', 'ë'), (0xCC, 'M', 'ì'), (0xCD, 'M', 'í'), (0xCE, 'M', 'î'), (0xCF, 'M', 'ï'), (0xD0, 'M', 'ð'), (0xD1, 'M', 'ñ'), (0xD2, 'M', 'ò'), (0xD3, 'M', 'ó'), (0xD4, 'M', 'ô'), (0xD5, 'M', 'õ'), (0xD6, 'M', 'ö'), (0xD7, 'V'), (0xD8, 'M', 'ø'), (0xD9, 'M', 'ù'), (0xDA, 'M', 'ú'), (0xDB, 'M', 'û'), (0xDC, 'M', 'ü'), (0xDD, 'M', 'ý'), (0xDE, 'M', 'þ'), (0xDF, 'D', 'ss'), (0xE0, 'V'), (0xE1, 'V'), (0xE2, 'V'), (0xE3, 'V'), (0xE4, 'V'), (0xE5, 'V'), (0xE6, 'V'), (0xE7, 'V'), (0xE8, 'V'), (0xE9, 'V'), (0xEA, 'V'), (0xEB, 'V'), (0xEC, 'V'), (0xED, 'V'), (0xEE, 'V'), (0xEF, 'V'), (0xF0, 'V'), (0xF1, 'V'), (0xF2, 'V'), (0xF3, 'V'), (0xF4, 'V'), (0xF5, 'V'), (0xF6, 'V'), (0xF7, 'V'), (0xF8, 'V'), (0xF9, 'V'), (0xFA, 'V'), (0xFB, 'V'), (0xFC, 'V'), (0xFD, 'V'), (0xFE, 'V'), (0xFF, 'V'), (0x100, 'M', 'ā'), (0x101, 'V'), (0x102, 'M', 'ă'), (0x103, 'V'), (0x104, 'M', 'ą'), (0x105, 'V'), (0x106, 'M', 'ć'), (0x107, 'V'), (0x108, 'M', 'ĉ'), (0x109, 'V'), (0x10A, 'M', 'ċ'), (0x10B, 'V'), (0x10C, 'M', 'č'), (0x10D, 'V'), (0x10E, 'M', 'ď'), (0x10F, 'V'), (0x110, 'M', 'đ'), (0x111, 'V'), (0x112, 'M', 'ē'), (0x113, 'V'), (0x114, 'M', 'ĕ'), (0x115, 'V'), (0x116, 'M', 'ė'), (0x117, 'V'), (0x118, 'M', 'ę'), (0x119, 'V'), (0x11A, 'M', 'ě'), (0x11B, 'V'), (0x11C, 'M', 'ĝ'), (0x11D, 'V'), (0x11E, 'M', 'ğ'), (0x11F, 'V'), (0x120, 'M', 'ġ'), (0x121, 'V'), (0x122, 'M', 'ģ'), (0x123, 'V'), (0x124, 'M', 'ĥ'), (0x125, 'V'), (0x126, 'M', 'ħ'), (0x127, 'V'), (0x128, 'M', 'ĩ'), (0x129, 'V'), (0x12A, 'M', 'ī'), (0x12B, 'V'), ] def _seg_3() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x12C, 'M', 'ĭ'), (0x12D, 'V'), (0x12E, 'M', 'į'), (0x12F, 'V'), (0x130, 'M', 'i̇'), (0x131, 'V'), (0x132, 'M', 'ij'), (0x134, 'M', 'ĵ'), (0x135, 'V'), (0x136, 'M', 'ķ'), (0x137, 'V'), (0x139, 'M', 'ĺ'), (0x13A, 'V'), (0x13B, 'M', 'ļ'), (0x13C, 'V'), (0x13D, 'M', 'ľ'), (0x13E, 'V'), (0x13F, 'M', 'l·'), (0x141, 'M', 'ł'), (0x142, 'V'), (0x143, 'M', 'ń'), (0x144, 'V'), (0x145, 'M', 'ņ'), (0x146, 'V'), (0x147, 'M', 'ň'), (0x148, 'V'), (0x149, 'M', 'ʼn'), (0x14A, 'M', 'ŋ'), (0x14B, 'V'), (0x14C, 'M', 'ō'), (0x14D, 'V'), (0x14E, 'M', 'ŏ'), (0x14F, 'V'), (0x150, 'M', 'ő'), (0x151, 'V'), (0x152, 'M', 'œ'), (0x153, 'V'), (0x154, 'M', 'ŕ'), (0x155, 'V'), (0x156, 'M', 'ŗ'), (0x157, 'V'), (0x158, 'M', 'ř'), (0x159, 'V'), (0x15A, 'M', 'ś'), (0x15B, 'V'), (0x15C, 'M', 'ŝ'), (0x15D, 'V'), (0x15E, 'M', 'ş'), (0x15F, 'V'), (0x160, 'M', 'š'), (0x161, 'V'), (0x162, 'M', 'ţ'), (0x163, 'V'), (0x164, 'M', 'ť'), (0x165, 'V'), (0x166, 'M', 'ŧ'), (0x167, 'V'), (0x168, 'M', 'ũ'), (0x169, 'V'), (0x16A, 'M', 'ū'), (0x16B, 'V'), (0x16C, 'M', 'ŭ'), (0x16D, 'V'), (0x16E, 'M', 'ů'), (0x16F, 'V'), (0x170, 'M', 'ű'), (0x171, 'V'), (0x172, 'M', 'ų'), (0x173, 'V'), (0x174, 'M', 'ŵ'), (0x175, 'V'), (0x176, 'M', 'ŷ'), (0x177, 'V'), (0x178, 'M', 'ÿ'), (0x179, 'M', 'ź'), (0x17A, 'V'), (0x17B, 'M', 'ż'), (0x17C, 'V'), (0x17D, 'M', 'ž'), (0x17E, 'V'), (0x17F, 'M', 's'), (0x180, 'V'), (0x181, 'M', 'ɓ'), (0x182, 'M', 'ƃ'), (0x183, 'V'), (0x184, 'M', 'ƅ'), (0x185, 'V'), (0x186, 'M', 'ɔ'), (0x187, 'M', 'ƈ'), (0x188, 'V'), (0x189, 'M', 'ɖ'), (0x18A, 'M', 'ɗ'), (0x18B, 'M', 'ƌ'), (0x18C, 'V'), (0x18E, 'M', 'ǝ'), (0x18F, 'M', 'ə'), (0x190, 'M', 'ɛ'), (0x191, 'M', 'ƒ'), (0x192, 'V'), (0x193, 'M', 'ɠ'), ] def _seg_4() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x194, 'M', 'ɣ'), (0x195, 'V'), (0x196, 'M', 'ɩ'), (0x197, 'M', 'ɨ'), (0x198, 'M', 'ƙ'), (0x199, 'V'), (0x19C, 'M', 'ɯ'), (0x19D, 'M', 'ɲ'), (0x19E, 'V'), (0x19F, 'M', 'ɵ'), (0x1A0, 'M', 'ơ'), (0x1A1, 'V'), (0x1A2, 'M', 'ƣ'), (0x1A3, 'V'), (0x1A4, 'M', 'ƥ'), (0x1A5, 'V'), (0x1A6, 'M', 'ʀ'), (0x1A7, 'M', 'ƨ'), (0x1A8, 'V'), (0x1A9, 'M', 'ʃ'), (0x1AA, 'V'), (0x1AC, 'M', 'ƭ'), (0x1AD, 'V'), (0x1AE, 'M', 'ʈ'), (0x1AF, 'M', 'ư'), (0x1B0, 'V'), (0x1B1, 'M', 'ʊ'), (0x1B2, 'M', 'ʋ'), (0x1B3, 'M', 'ƴ'), (0x1B4, 'V'), (0x1B5, 'M', 'ƶ'), (0x1B6, 'V'), (0x1B7, 'M', 'ʒ'), (0x1B8, 'M', 'ƹ'), (0x1B9, 'V'), (0x1BC, 'M', 'ƽ'), (0x1BD, 'V'), (0x1C4, 'M', 'dž'), (0x1C7, 'M', 'lj'), (0x1CA, 'M', 'nj'), (0x1CD, 'M', 'ǎ'), (0x1CE, 'V'), (0x1CF, 'M', 'ǐ'), (0x1D0, 'V'), (0x1D1, 'M', 'ǒ'), (0x1D2, 'V'), (0x1D3, 'M', 'ǔ'), (0x1D4, 'V'), (0x1D5, 'M', 'ǖ'), (0x1D6, 'V'), (0x1D7, 'M', 'ǘ'), (0x1D8, 'V'), (0x1D9, 'M', 'ǚ'), (0x1DA, 'V'), (0x1DB, 'M', 'ǜ'), (0x1DC, 'V'), (0x1DE, 'M', 'ǟ'), (0x1DF, 'V'), (0x1E0, 'M', 'ǡ'), (0x1E1, 'V'), (0x1E2, 'M', 'ǣ'), (0x1E3, 'V'), (0x1E4, 'M', 'ǥ'), (0x1E5, 'V'), (0x1E6, 'M', 'ǧ'), (0x1E7, 'V'), (0x1E8, 'M', 'ǩ'), (0x1E9, 'V'), (0x1EA, 'M', 'ǫ'), (0x1EB, 'V'), (0x1EC, 'M', 'ǭ'), (0x1ED, 'V'), (0x1EE, 'M', 'ǯ'), (0x1EF, 'V'), (0x1F1, 'M', 'dz'), (0x1F4, 'M', 'ǵ'), (0x1F5, 'V'), (0x1F6, 'M', 'ƕ'), (0x1F7, 'M', 'ƿ'), (0x1F8, 'M', 'ǹ'), (0x1F9, 'V'), (0x1FA, 'M', 'ǻ'), (0x1FB, 'V'), (0x1FC, 'M', 'ǽ'), (0x1FD, 'V'), (0x1FE, 'M', 'ǿ'), (0x1FF, 'V'), (0x200, 'M', 'ȁ'), (0x201, 'V'), (0x202, 'M', 'ȃ'), (0x203, 'V'), (0x204, 'M', 'ȅ'), (0x205, 'V'), (0x206, 'M', 'ȇ'), (0x207, 'V'), (0x208, 'M', 'ȉ'), (0x209, 'V'), (0x20A, 'M', 'ȋ'), (0x20B, 'V'), (0x20C, 'M', 'ȍ'), ] def _seg_5() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x20D, 'V'), (0x20E, 'M', 'ȏ'), (0x20F, 'V'), (0x210, 'M', 'ȑ'), (0x211, 'V'), (0x212, 'M', 'ȓ'), (0x213, 'V'), (0x214, 'M', 'ȕ'), (0x215, 'V'), (0x216, 'M', 'ȗ'), (0x217, 'V'), (0x218, 'M', 'ș'), (0x219, 'V'), (0x21A, 'M', 'ț'), (0x21B, 'V'), (0x21C, 'M', 'ȝ'), (0x21D, 'V'), (0x21E, 'M', 'ȟ'), (0x21F, 'V'), (0x220, 'M', 'ƞ'), (0x221, 'V'), (0x222, 'M', 'ȣ'), (0x223, 'V'), (0x224, 'M', 'ȥ'), (0x225, 'V'), (0x226, 'M', 'ȧ'), (0x227, 'V'), (0x228, 'M', 'ȩ'), (0x229, 'V'), (0x22A, 'M', 'ȫ'), (0x22B, 'V'), (0x22C, 'M', 'ȭ'), (0x22D, 'V'), (0x22E, 'M', 'ȯ'), (0x22F, 'V'), (0x230, 'M', 'ȱ'), (0x231, 'V'), (0x232, 'M', 'ȳ'), (0x233, 'V'), (0x23A, 'M', 'ⱥ'), (0x23B, 'M', 'ȼ'), (0x23C, 'V'), (0x23D, 'M', 'ƚ'), (0x23E, 'M', 'ⱦ'), (0x23F, 'V'), (0x241, 'M', 'ɂ'), (0x242, 'V'), (0x243, 'M', 'ƀ'), (0x244, 'M', 'ʉ'), (0x245, 'M', 'ʌ'), (0x246, 'M', 'ɇ'), (0x247, 'V'), (0x248, 'M', 'ɉ'), (0x249, 'V'), (0x24A, 'M', 'ɋ'), (0x24B, 'V'), (0x24C, 'M', 'ɍ'), (0x24D, 'V'), (0x24E, 'M', 'ɏ'), (0x24F, 'V'), (0x2B0, 'M', 'h'), (0x2B1, 'M', 'ɦ'), (0x2B2, 'M', 'j'), (0x2B3, 'M', 'r'), (0x2B4, 'M', 'ɹ'), (0x2B5, 'M', 'ɻ'), (0x2B6, 'M', 'ʁ'), (0x2B7, 'M', 'w'), (0x2B8, 'M', 'y'), (0x2B9, 'V'), (0x2D8, '3', ' ̆'), (0x2D9, '3', ' ̇'), (0x2DA, '3', ' ̊'), (0x2DB, '3', ' ̨'), (0x2DC, '3', ' ̃'), (0x2DD, '3', ' ̋'), (0x2DE, 'V'), (0x2E0, 'M', 'ɣ'), (0x2E1, 'M', 'l'), (0x2E2, 'M', 's'), (0x2E3, 'M', 'x'), (0x2E4, 'M', 'ʕ'), (0x2E5, 'V'), (0x340, 'M', '̀'), (0x341, 'M', '́'), (0x342, 'V'), (0x343, 'M', '̓'), (0x344, 'M', '̈́'), (0x345, 'M', 'ι'), (0x346, 'V'), (0x34F, 'I'), (0x350, 'V'), (0x370, 'M', 'ͱ'), (0x371, 'V'), (0x372, 'M', 'ͳ'), (0x373, 'V'), (0x374, 'M', 'ʹ'), (0x375, 'V'), (0x376, 'M', 'ͷ'), (0x377, 'V'), ] def _seg_6() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x378, 'X'), (0x37A, '3', ' ι'), (0x37B, 'V'), (0x37E, '3', ';'), (0x37F, 'M', 'ϳ'), (0x380, 'X'), (0x384, '3', ' ́'), (0x385, '3', ' ̈́'), (0x386, 'M', 'ά'), (0x387, 'M', '·'), (0x388, 'M', 'έ'), (0x389, 'M', 'ή'), (0x38A, 'M', 'ί'), (0x38B, 'X'), (0x38C, 'M', 'ό'), (0x38D, 'X'), (0x38E, 'M', 'ύ'), (0x38F, 'M', 'ώ'), (0x390, 'V'), (0x391, 'M', 'α'), (0x392, 'M', 'β'), (0x393, 'M', 'γ'), (0x394, 'M', 'δ'), (0x395, 'M', 'ε'), (0x396, 'M', 'ζ'), (0x397, 'M', 'η'), (0x398, 'M', 'θ'), (0x399, 'M', 'ι'), (0x39A, 'M', 'κ'), (0x39B, 'M', 'λ'), (0x39C, 'M', 'μ'), (0x39D, 'M', 'ν'), (0x39E, 'M', 'ξ'), (0x39F, 'M', 'ο'), (0x3A0, 'M', 'π'), (0x3A1, 'M', 'ρ'), (0x3A2, 'X'), (0x3A3, 'M', 'σ'), (0x3A4, 'M', 'τ'), (0x3A5, 'M', 'υ'), (0x3A6, 'M', 'φ'), (0x3A7, 'M', 'χ'), (0x3A8, 'M', 'ψ'), (0x3A9, 'M', 'ω'), (0x3AA, 'M', 'ϊ'), (0x3AB, 'M', 'ϋ'), (0x3AC, 'V'), (0x3C2, 'D', 'σ'), (0x3C3, 'V'), (0x3CF, 'M', 'ϗ'), (0x3D0, 'M', 'β'), (0x3D1, 'M', 'θ'), (0x3D2, 'M', 'υ'), (0x3D3, 'M', 'ύ'), (0x3D4, 'M', 'ϋ'), (0x3D5, 'M', 'φ'), (0x3D6, 'M', 'π'), (0x3D7, 'V'), (0x3D8, 'M', 'ϙ'), (0x3D9, 'V'), (0x3DA, 'M', 'ϛ'), (0x3DB, 'V'), (0x3DC, 'M', 'ϝ'), (0x3DD, 'V'), (0x3DE, 'M', 'ϟ'), (0x3DF, 'V'), (0x3E0, 'M', 'ϡ'), (0x3E1, 'V'), (0x3E2, 'M', 'ϣ'), (0x3E3, 'V'), (0x3E4, 'M', 'ϥ'), (0x3E5, 'V'), (0x3E6, 'M', 'ϧ'), (0x3E7, 'V'), (0x3E8, 'M', 'ϩ'), (0x3E9, 'V'), (0x3EA, 'M', 'ϫ'), (0x3EB, 'V'), (0x3EC, 'M', 'ϭ'), (0x3ED, 'V'), (0x3EE, 'M', 'ϯ'), (0x3EF, 'V'), (0x3F0, 'M', 'κ'), (0x3F1, 'M', 'ρ'), (0x3F2, 'M', 'σ'), (0x3F3, 'V'), (0x3F4, 'M', 'θ'), (0x3F5, 'M', 'ε'), (0x3F6, 'V'), (0x3F7, 'M', 'ϸ'), (0x3F8, 'V'), (0x3F9, 'M', 'σ'), (0x3FA, 'M', 'ϻ'), (0x3FB, 'V'), (0x3FD, 'M', 'ͻ'), (0x3FE, 'M', 'ͼ'), (0x3FF, 'M', 'ͽ'), (0x400, 'M', 'ѐ'), (0x401, 'M', 'ё'), (0x402, 'M', 'ђ'), ] def _seg_7() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x403, 'M', 'ѓ'), (0x404, 'M', 'є'), (0x405, 'M', 'ѕ'), (0x406, 'M', 'і'), (0x407, 'M', 'ї'), (0x408, 'M', 'ј'), (0x409, 'M', 'љ'), (0x40A, 'M', 'њ'), (0x40B, 'M', 'ћ'), (0x40C, 'M', 'ќ'), (0x40D, 'M', 'ѝ'), (0x40E, 'M', 'ў'), (0x40F, 'M', 'џ'), (0x410, 'M', 'а'), (0x411, 'M', 'б'), (0x412, 'M', 'в'), (0x413, 'M', 'г'), (0x414, 'M', 'д'), (0x415, 'M', 'е'), (0x416, 'M', 'ж'), (0x417, 'M', 'з'), (0x418, 'M', 'и'), (0x419, 'M', 'й'), (0x41A, 'M', 'к'), (0x41B, 'M', 'л'), (0x41C, 'M', 'м'), (0x41D, 'M', 'н'), (0x41E, 'M', 'о'), (0x41F, 'M', 'п'), (0x420, 'M', 'р'), (0x421, 'M', 'с'), (0x422, 'M', 'т'), (0x423, 'M', 'у'), (0x424, 'M', 'ф'), (0x425, 'M', 'х'), (0x426, 'M', 'ц'), (0x427, 'M', 'ч'), (0x428, 'M', 'ш'), (0x429, 'M', 'щ'), (0x42A, 'M', 'ъ'), (0x42B, 'M', 'ы'), (0x42C, 'M', 'ь'), (0x42D, 'M', 'э'), (0x42E, 'M', 'ю'), (0x42F, 'M', 'я'), (0x430, 'V'), (0x460, 'M', 'ѡ'), (0x461, 'V'), (0x462, 'M', 'ѣ'), (0x463, 'V'), (0x464, 'M', 'ѥ'), (0x465, 'V'), (0x466, 'M', 'ѧ'), (0x467, 'V'), (0x468, 'M', 'ѩ'), (0x469, 'V'), (0x46A, 'M', 'ѫ'), (0x46B, 'V'), (0x46C, 'M', 'ѭ'), (0x46D, 'V'), (0x46E, 'M', 'ѯ'), (0x46F, 'V'), (0x470, 'M', 'ѱ'), (0x471, 'V'), (0x472, 'M', 'ѳ'), (0x473, 'V'), (0x474, 'M', 'ѵ'), (0x475, 'V'), (0x476, 'M', 'ѷ'), (0x477, 'V'), (0x478, 'M', 'ѹ'), (0x479, 'V'), (0x47A, 'M', 'ѻ'), (0x47B, 'V'), (0x47C, 'M', 'ѽ'), (0x47D, 'V'), (0x47E, 'M', 'ѿ'), (0x47F, 'V'), (0x480, 'M', 'ҁ'), (0x481, 'V'), (0x48A, 'M', 'ҋ'), (0x48B, 'V'), (0x48C, 'M', 'ҍ'), (0x48D, 'V'), (0x48E, 'M', 'ҏ'), (0x48F, 'V'), (0x490, 'M', 'ґ'), (0x491, 'V'), (0x492, 'M', 'ғ'), (0x493, 'V'), (0x494, 'M', 'ҕ'), (0x495, 'V'), (0x496, 'M', 'җ'), (0x497, 'V'), (0x498, 'M', 'ҙ'), (0x499, 'V'), (0x49A, 'M', 'қ'), (0x49B, 'V'), (0x49C, 'M', 'ҝ'), (0x49D, 'V'), ] def _seg_8() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x49E, 'M', 'ҟ'), (0x49F, 'V'), (0x4A0, 'M', 'ҡ'), (0x4A1, 'V'), (0x4A2, 'M', 'ң'), (0x4A3, 'V'), (0x4A4, 'M', 'ҥ'), (0x4A5, 'V'), (0x4A6, 'M', 'ҧ'), (0x4A7, 'V'), (0x4A8, 'M', 'ҩ'), (0x4A9, 'V'), (0x4AA, 'M', 'ҫ'), (0x4AB, 'V'), (0x4AC, 'M', 'ҭ'), (0x4AD, 'V'), (0x4AE, 'M', 'ү'), (0x4AF, 'V'), (0x4B0, 'M', 'ұ'), (0x4B1, 'V'), (0x4B2, 'M', 'ҳ'), (0x4B3, 'V'), (0x4B4, 'M', 'ҵ'), (0x4B5, 'V'), (0x4B6, 'M', 'ҷ'), (0x4B7, 'V'), (0x4B8, 'M', 'ҹ'), (0x4B9, 'V'), (0x4BA, 'M', 'һ'), (0x4BB, 'V'), (0x4BC, 'M', 'ҽ'), (0x4BD, 'V'), (0x4BE, 'M', 'ҿ'), (0x4BF, 'V'), (0x4C0, 'X'), (0x4C1, 'M', 'ӂ'), (0x4C2, 'V'), (0x4C3, 'M', 'ӄ'), (0x4C4, 'V'), (0x4C5, 'M', 'ӆ'), (0x4C6, 'V'), (0x4C7, 'M', 'ӈ'), (0x4C8, 'V'), (0x4C9, 'M', 'ӊ'), (0x4CA, 'V'), (0x4CB, 'M', 'ӌ'), (0x4CC, 'V'), (0x4CD, 'M', 'ӎ'), (0x4CE, 'V'), (0x4D0, 'M', 'ӑ'), (0x4D1, 'V'), (0x4D2, 'M', 'ӓ'), (0x4D3, 'V'), (0x4D4, 'M', 'ӕ'), (0x4D5, 'V'), (0x4D6, 'M', 'ӗ'), (0x4D7, 'V'), (0x4D8, 'M', 'ә'), (0x4D9, 'V'), (0x4DA, 'M', 'ӛ'), (0x4DB, 'V'), (0x4DC, 'M', 'ӝ'), (0x4DD, 'V'), (0x4DE, 'M', 'ӟ'), (0x4DF, 'V'), (0x4E0, 'M', 'ӡ'), (0x4E1, 'V'), (0x4E2, 'M', 'ӣ'), (0x4E3, 'V'), (0x4E4, 'M', 'ӥ'), (0x4E5, 'V'), (0x4E6, 'M', 'ӧ'), (0x4E7, 'V'), (0x4E8, 'M', 'ө'), (0x4E9, 'V'), (0x4EA, 'M', 'ӫ'), (0x4EB, 'V'), (0x4EC, 'M', 'ӭ'), (0x4ED, 'V'), (0x4EE, 'M', 'ӯ'), (0x4EF, 'V'), (0x4F0, 'M', 'ӱ'), (0x4F1, 'V'), (0x4F2, 'M', 'ӳ'), (0x4F3, 'V'), (0x4F4, 'M', 'ӵ'), (0x4F5, 'V'), (0x4F6, 'M', 'ӷ'), (0x4F7, 'V'), (0x4F8, 'M', 'ӹ'), (0x4F9, 'V'), (0x4FA, 'M', 'ӻ'), (0x4FB, 'V'), (0x4FC, 'M', 'ӽ'), (0x4FD, 'V'), (0x4FE, 'M', 'ӿ'), (0x4FF, 'V'), (0x500, 'M', 'ԁ'), (0x501, 'V'), (0x502, 'M', 'ԃ'), ] def _seg_9() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x503, 'V'), (0x504, 'M', 'ԅ'), (0x505, 'V'), (0x506, 'M', 'ԇ'), (0x507, 'V'), (0x508, 'M', 'ԉ'), (0x509, 'V'), (0x50A, 'M', 'ԋ'), (0x50B, 'V'), (0x50C, 'M', 'ԍ'), (0x50D, 'V'), (0x50E, 'M', 'ԏ'), (0x50F, 'V'), (0x510, 'M', 'ԑ'), (0x511, 'V'), (0x512, 'M', 'ԓ'), (0x513, 'V'), (0x514, 'M', 'ԕ'), (0x515, 'V'), (0x516, 'M', 'ԗ'), (0x517, 'V'), (0x518, 'M', 'ԙ'), (0x519, 'V'), (0x51A, 'M', 'ԛ'), (0x51B, 'V'), (0x51C, 'M', 'ԝ'), (0x51D, 'V'), (0x51E, 'M', 'ԟ'), (0x51F, 'V'), (0x520, 'M', 'ԡ'), (0x521, 'V'), (0x522, 'M', 'ԣ'), (0x523, 'V'), (0x524, 'M', 'ԥ'), (0x525, 'V'), (0x526, 'M', 'ԧ'), (0x527, 'V'), (0x528, 'M', 'ԩ'), (0x529, 'V'), (0x52A, 'M', 'ԫ'), (0x52B, 'V'), (0x52C, 'M', 'ԭ'), (0x52D, 'V'), (0x52E, 'M', 'ԯ'), (0x52F, 'V'), (0x530, 'X'), (0x531, 'M', 'ա'), (0x532, 'M', 'բ'), (0x533, 'M', 'գ'), (0x534, 'M', 'դ'), (0x535, 'M', 'ե'), (0x536, 'M', 'զ'), (0x537, 'M', 'է'), (0x538, 'M', 'ը'), (0x539, 'M', 'թ'), (0x53A, 'M', 'ժ'), (0x53B, 'M', 'ի'), (0x53C, 'M', 'լ'), (0x53D, 'M', 'խ'), (0x53E, 'M', 'ծ'), (0x53F, 'M', 'կ'), (0x540, 'M', 'հ'), (0x541, 'M', 'ձ'), (0x542, 'M', 'ղ'), (0x543, 'M', 'ճ'), (0x544, 'M', 'մ'), (0x545, 'M', 'յ'), (0x546, 'M', 'ն'), (0x547, 'M', 'շ'), (0x548, 'M', 'ո'), (0x549, 'M', 'չ'), (0x54A, 'M', 'պ'), (0x54B, 'M', 'ջ'), (0x54C, 'M', 'ռ'), (0x54D, 'M', 'ս'), (0x54E, 'M', 'վ'), (0x54F, 'M', 'տ'), (0x550, 'M', 'ր'), (0x551, 'M', 'ց'), (0x552, 'M', 'ւ'), (0x553, 'M', 'փ'), (0x554, 'M', 'ք'), (0x555, 'M', 'օ'), (0x556, 'M', 'ֆ'), (0x557, 'X'), (0x559, 'V'), (0x587, 'M', 'եւ'), (0x588, 'V'), (0x58B, 'X'), (0x58D, 'V'), (0x590, 'X'), (0x591, 'V'), (0x5C8, 'X'), (0x5D0, 'V'), (0x5EB, 'X'), (0x5EF, 'V'), (0x5F5, 'X'), (0x606, 'V'), (0x61C, 'X'), (0x61D, 'V'), ] def _seg_10() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x675, 'M', 'اٴ'), (0x676, 'M', 'وٴ'), (0x677, 'M', 'ۇٴ'), (0x678, 'M', 'يٴ'), (0x679, 'V'), (0x6DD, 'X'), (0x6DE, 'V'), (0x70E, 'X'), (0x710, 'V'), (0x74B, 'X'), (0x74D, 'V'), (0x7B2, 'X'), (0x7C0, 'V'), (0x7FB, 'X'), (0x7FD, 'V'), (0x82E, 'X'), (0x830, 'V'), (0x83F, 'X'), (0x840, 'V'), (0x85C, 'X'), (0x85E, 'V'), (0x85F, 'X'), (0x860, 'V'), (0x86B, 'X'), (0x870, 'V'), (0x88F, 'X'), (0x898, 'V'), (0x8E2, 'X'), (0x8E3, 'V'), (0x958, 'M', 'क़'), (0x959, 'M', 'ख़'), (0x95A, 'M', 'ग़'), (0x95B, 'M', 'ज़'), (0x95C, 'M', 'ड़'), (0x95D, 'M', 'ढ़'), (0x95E, 'M', 'फ़'), (0x95F, 'M', 'य़'), (0x960, 'V'), (0x984, 'X'), (0x985, 'V'), (0x98D, 'X'), (0x98F, 'V'), (0x991, 'X'), (0x993, 'V'), (0x9A9, 'X'), (0x9AA, 'V'), (0x9B1, 'X'), (0x9B2, 'V'), (0x9B3, 'X'), (0x9B6, 'V'), (0x9BA, 'X'), (0x9BC, 'V'), (0x9C5, 'X'), (0x9C7, 'V'), (0x9C9, 'X'), (0x9CB, 'V'), (0x9CF, 'X'), (0x9D7, 'V'), (0x9D8, 'X'), (0x9DC, 'M', 'ড়'), (0x9DD, 'M', 'ঢ়'), (0x9DE, 'X'), (0x9DF, 'M', 'য়'), (0x9E0, 'V'), (0x9E4, 'X'), (0x9E6, 'V'), (0x9FF, 'X'), (0xA01, 'V'), (0xA04, 'X'), (0xA05, 'V'), (0xA0B, 'X'), (0xA0F, 'V'), (0xA11, 'X'), (0xA13, 'V'), (0xA29, 'X'), (0xA2A, 'V'), (0xA31, 'X'), (0xA32, 'V'), (0xA33, 'M', 'ਲ਼'), (0xA34, 'X'), (0xA35, 'V'), (0xA36, 'M', 'ਸ਼'), (0xA37, 'X'), (0xA38, 'V'), (0xA3A, 'X'), (0xA3C, 'V'), (0xA3D, 'X'), (0xA3E, 'V'), (0xA43, 'X'), (0xA47, 'V'), (0xA49, 'X'), (0xA4B, 'V'), (0xA4E, 'X'), (0xA51, 'V'), (0xA52, 'X'), (0xA59, 'M', 'ਖ਼'), (0xA5A, 'M', 'ਗ਼'), (0xA5B, 'M', 'ਜ਼'), (0xA5C, 'V'), (0xA5D, 'X'), ] def _seg_11() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA5E, 'M', 'ਫ਼'), (0xA5F, 'X'), (0xA66, 'V'), (0xA77, 'X'), (0xA81, 'V'), (0xA84, 'X'), (0xA85, 'V'), (0xA8E, 'X'), (0xA8F, 'V'), (0xA92, 'X'), (0xA93, 'V'), (0xAA9, 'X'), (0xAAA, 'V'), (0xAB1, 'X'), (0xAB2, 'V'), (0xAB4, 'X'), (0xAB5, 'V'), (0xABA, 'X'), (0xABC, 'V'), (0xAC6, 'X'), (0xAC7, 'V'), (0xACA, 'X'), (0xACB, 'V'), (0xACE, 'X'), (0xAD0, 'V'), (0xAD1, 'X'), (0xAE0, 'V'), (0xAE4, 'X'), (0xAE6, 'V'), (0xAF2, 'X'), (0xAF9, 'V'), (0xB00, 'X'), (0xB01, 'V'), (0xB04, 'X'), (0xB05, 'V'), (0xB0D, 'X'), (0xB0F, 'V'), (0xB11, 'X'), (0xB13, 'V'), (0xB29, 'X'), (0xB2A, 'V'), (0xB31, 'X'), (0xB32, 'V'), (0xB34, 'X'), (0xB35, 'V'), (0xB3A, 'X'), (0xB3C, 'V'), (0xB45, 'X'), (0xB47, 'V'), (0xB49, 'X'), (0xB4B, 'V'), (0xB4E, 'X'), (0xB55, 'V'), (0xB58, 'X'), (0xB5C, 'M', 'ଡ଼'), (0xB5D, 'M', 'ଢ଼'), (0xB5E, 'X'), (0xB5F, 'V'), (0xB64, 'X'), (0xB66, 'V'), (0xB78, 'X'), (0xB82, 'V'), (0xB84, 'X'), (0xB85, 'V'), (0xB8B, 'X'), (0xB8E, 'V'), (0xB91, 'X'), (0xB92, 'V'), (0xB96, 'X'), (0xB99, 'V'), (0xB9B, 'X'), (0xB9C, 'V'), (0xB9D, 'X'), (0xB9E, 'V'), (0xBA0, 'X'), (0xBA3, 'V'), (0xBA5, 'X'), (0xBA8, 'V'), (0xBAB, 'X'), (0xBAE, 'V'), (0xBBA, 'X'), (0xBBE, 'V'), (0xBC3, 'X'), (0xBC6, 'V'), (0xBC9, 'X'), (0xBCA, 'V'), (0xBCE, 'X'), (0xBD0, 'V'), (0xBD1, 'X'), (0xBD7, 'V'), (0xBD8, 'X'), (0xBE6, 'V'), (0xBFB, 'X'), (0xC00, 'V'), (0xC0D, 'X'), (0xC0E, 'V'), (0xC11, 'X'), (0xC12, 'V'), (0xC29, 'X'), (0xC2A, 'V'), ] def _seg_12() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xC3A, 'X'), (0xC3C, 'V'), (0xC45, 'X'), (0xC46, 'V'), (0xC49, 'X'), (0xC4A, 'V'), (0xC4E, 'X'), (0xC55, 'V'), (0xC57, 'X'), (0xC58, 'V'), (0xC5B, 'X'), (0xC5D, 'V'), (0xC5E, 'X'), (0xC60, 'V'), (0xC64, 'X'), (0xC66, 'V'), (0xC70, 'X'), (0xC77, 'V'), (0xC8D, 'X'), (0xC8E, 'V'), (0xC91, 'X'), (0xC92, 'V'), (0xCA9, 'X'), (0xCAA, 'V'), (0xCB4, 'X'), (0xCB5, 'V'), (0xCBA, 'X'), (0xCBC, 'V'), (0xCC5, 'X'), (0xCC6, 'V'), (0xCC9, 'X'), (0xCCA, 'V'), (0xCCE, 'X'), (0xCD5, 'V'), (0xCD7, 'X'), (0xCDD, 'V'), (0xCDF, 'X'), (0xCE0, 'V'), (0xCE4, 'X'), (0xCE6, 'V'), (0xCF0, 'X'), (0xCF1, 'V'), (0xCF3, 'X'), (0xD00, 'V'), (0xD0D, 'X'), (0xD0E, 'V'), (0xD11, 'X'), (0xD12, 'V'), (0xD45, 'X'), (0xD46, 'V'), (0xD49, 'X'), (0xD4A, 'V'), (0xD50, 'X'), (0xD54, 'V'), (0xD64, 'X'), (0xD66, 'V'), (0xD80, 'X'), (0xD81, 'V'), (0xD84, 'X'), (0xD85, 'V'), (0xD97, 'X'), (0xD9A, 'V'), (0xDB2, 'X'), (0xDB3, 'V'), (0xDBC, 'X'), (0xDBD, 'V'), (0xDBE, 'X'), (0xDC0, 'V'), (0xDC7, 'X'), (0xDCA, 'V'), (0xDCB, 'X'), (0xDCF, 'V'), (0xDD5, 'X'), (0xDD6, 'V'), (0xDD7, 'X'), (0xDD8, 'V'), (0xDE0, 'X'), (0xDE6, 'V'), (0xDF0, 'X'), (0xDF2, 'V'), (0xDF5, 'X'), (0xE01, 'V'), (0xE33, 'M', 'ํา'), (0xE34, 'V'), (0xE3B, 'X'), (0xE3F, 'V'), (0xE5C, 'X'), (0xE81, 'V'), (0xE83, 'X'), (0xE84, 'V'), (0xE85, 'X'), (0xE86, 'V'), (0xE8B, 'X'), (0xE8C, 'V'), (0xEA4, 'X'), (0xEA5, 'V'), (0xEA6, 'X'), (0xEA7, 'V'), (0xEB3, 'M', 'ໍາ'), (0xEB4, 'V'), ] def _seg_13() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xEBE, 'X'), (0xEC0, 'V'), (0xEC5, 'X'), (0xEC6, 'V'), (0xEC7, 'X'), (0xEC8, 'V'), (0xECE, 'X'), (0xED0, 'V'), (0xEDA, 'X'), (0xEDC, 'M', 'ຫນ'), (0xEDD, 'M', 'ຫມ'), (0xEDE, 'V'), (0xEE0, 'X'), (0xF00, 'V'), (0xF0C, 'M', '་'), (0xF0D, 'V'), (0xF43, 'M', 'གྷ'), (0xF44, 'V'), (0xF48, 'X'), (0xF49, 'V'), (0xF4D, 'M', 'ཌྷ'), (0xF4E, 'V'), (0xF52, 'M', 'དྷ'), (0xF53, 'V'), (0xF57, 'M', 'བྷ'), (0xF58, 'V'), (0xF5C, 'M', 'ཛྷ'), (0xF5D, 'V'), (0xF69, 'M', 'ཀྵ'), (0xF6A, 'V'), (0xF6D, 'X'), (0xF71, 'V'), (0xF73, 'M', 'ཱི'), (0xF74, 'V'), (0xF75, 'M', 'ཱུ'), (0xF76, 'M', 'ྲྀ'), (0xF77, 'M', 'ྲཱྀ'), (0xF78, 'M', 'ླྀ'), (0xF79, 'M', 'ླཱྀ'), (0xF7A, 'V'), (0xF81, 'M', 'ཱྀ'), (0xF82, 'V'), (0xF93, 'M', 'ྒྷ'), (0xF94, 'V'), (0xF98, 'X'), (0xF99, 'V'), (0xF9D, 'M', 'ྜྷ'), (0xF9E, 'V'), (0xFA2, 'M', 'ྡྷ'), (0xFA3, 'V'), (0xFA7, 'M', 'ྦྷ'), (0xFA8, 'V'), (0xFAC, 'M', 'ྫྷ'), (0xFAD, 'V'), (0xFB9, 'M', 'ྐྵ'), (0xFBA, 'V'), (0xFBD, 'X'), (0xFBE, 'V'), (0xFCD, 'X'), (0xFCE, 'V'), (0xFDB, 'X'), (0x1000, 'V'), (0x10A0, 'X'), (0x10C7, 'M', 'ⴧ'), (0x10C8, 'X'), (0x10CD, 'M', 'ⴭ'), (0x10CE, 'X'), (0x10D0, 'V'), (0x10FC, 'M', 'ნ'), (0x10FD, 'V'), (0x115F, 'X'), (0x1161, 'V'), (0x1249, 'X'), (0x124A, 'V'), (0x124E, 'X'), (0x1250, 'V'), (0x1257, 'X'), (0x1258, 'V'), (0x1259, 'X'), (0x125A, 'V'), (0x125E, 'X'), (0x1260, 'V'), (0x1289, 'X'), (0x128A, 'V'), (0x128E, 'X'), (0x1290, 'V'), (0x12B1, 'X'), (0x12B2, 'V'), (0x12B6, 'X'), (0x12B8, 'V'), (0x12BF, 'X'), (0x12C0, 'V'), (0x12C1, 'X'), (0x12C2, 'V'), (0x12C6, 'X'), (0x12C8, 'V'), (0x12D7, 'X'), (0x12D8, 'V'), (0x1311, 'X'), (0x1312, 'V'), ] def _seg_14() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1316, 'X'), (0x1318, 'V'), (0x135B, 'X'), (0x135D, 'V'), (0x137D, 'X'), (0x1380, 'V'), (0x139A, 'X'), (0x13A0, 'V'), (0x13F6, 'X'), (0x13F8, 'M', 'Ᏸ'), (0x13F9, 'M', 'Ᏹ'), (0x13FA, 'M', 'Ᏺ'), (0x13FB, 'M', 'Ᏻ'), (0x13FC, 'M', 'Ᏼ'), (0x13FD, 'M', 'Ᏽ'), (0x13FE, 'X'), (0x1400, 'V'), (0x1680, 'X'), (0x1681, 'V'), (0x169D, 'X'), (0x16A0, 'V'), (0x16F9, 'X'), (0x1700, 'V'), (0x1716, 'X'), (0x171F, 'V'), (0x1737, 'X'), (0x1740, 'V'), (0x1754, 'X'), (0x1760, 'V'), (0x176D, 'X'), (0x176E, 'V'), (0x1771, 'X'), (0x1772, 'V'), (0x1774, 'X'), (0x1780, 'V'), (0x17B4, 'X'), (0x17B6, 'V'), (0x17DE, 'X'), (0x17E0, 'V'), (0x17EA, 'X'), (0x17F0, 'V'), (0x17FA, 'X'), (0x1800, 'V'), (0x1806, 'X'), (0x1807, 'V'), (0x180B, 'I'), (0x180E, 'X'), (0x180F, 'I'), (0x1810, 'V'), (0x181A, 'X'), (0x1820, 'V'), (0x1879, 'X'), (0x1880, 'V'), (0x18AB, 'X'), (0x18B0, 'V'), (0x18F6, 'X'), (0x1900, 'V'), (0x191F, 'X'), (0x1920, 'V'), (0x192C, 'X'), (0x1930, 'V'), (0x193C, 'X'), (0x1940, 'V'), (0x1941, 'X'), (0x1944, 'V'), (0x196E, 'X'), (0x1970, 'V'), (0x1975, 'X'), (0x1980, 'V'), (0x19AC, 'X'), (0x19B0, 'V'), (0x19CA, 'X'), (0x19D0, 'V'), (0x19DB, 'X'), (0x19DE, 'V'), (0x1A1C, 'X'), (0x1A1E, 'V'), (0x1A5F, 'X'), (0x1A60, 'V'), (0x1A7D, 'X'), (0x1A7F, 'V'), (0x1A8A, 'X'), (0x1A90, 'V'), (0x1A9A, 'X'), (0x1AA0, 'V'), (0x1AAE, 'X'), (0x1AB0, 'V'), (0x1ACF, 'X'), (0x1B00, 'V'), (0x1B4D, 'X'), (0x1B50, 'V'), (0x1B7F, 'X'), (0x1B80, 'V'), (0x1BF4, 'X'), (0x1BFC, 'V'), (0x1C38, 'X'), (0x1C3B, 'V'), (0x1C4A, 'X'), (0x1C4D, 'V'), (0x1C80, 'M', 'в'), ] def _seg_15() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1C81, 'M', 'д'), (0x1C82, 'M', 'о'), (0x1C83, 'M', 'с'), (0x1C84, 'M', 'т'), (0x1C86, 'M', 'ъ'), (0x1C87, 'M', 'ѣ'), (0x1C88, 'M', 'ꙋ'), (0x1C89, 'X'), (0x1C90, 'M', 'ა'), (0x1C91, 'M', 'ბ'), (0x1C92, 'M', 'გ'), (0x1C93, 'M', 'დ'), (0x1C94, 'M', 'ე'), (0x1C95, 'M', 'ვ'), (0x1C96, 'M', 'ზ'), (0x1C97, 'M', 'თ'), (0x1C98, 'M', 'ი'), (0x1C99, 'M', 'კ'), (0x1C9A, 'M', 'ლ'), (0x1C9B, 'M', 'მ'), (0x1C9C, 'M', 'ნ'), (0x1C9D, 'M', 'ო'), (0x1C9E, 'M', 'პ'), (0x1C9F, 'M', 'ჟ'), (0x1CA0, 'M', 'რ'), (0x1CA1, 'M', 'ს'), (0x1CA2, 'M', 'ტ'), (0x1CA3, 'M', 'უ'), (0x1CA4, 'M', 'ფ'), (0x1CA5, 'M', 'ქ'), (0x1CA6, 'M', 'ღ'), (0x1CA7, 'M', 'ყ'), (0x1CA8, 'M', 'შ'), (0x1CA9, 'M', 'ჩ'), (0x1CAA, 'M', 'ც'), (0x1CAB, 'M', 'ძ'), (0x1CAC, 'M', 'წ'), (0x1CAD, 'M', 'ჭ'), (0x1CAE, 'M', 'ხ'), (0x1CAF, 'M', 'ჯ'), (0x1CB0, 'M', 'ჰ'), (0x1CB1, 'M', 'ჱ'), (0x1CB2, 'M', 'ჲ'), (0x1CB3, 'M', 'ჳ'), (0x1CB4, 'M', 'ჴ'), (0x1CB5, 'M', 'ჵ'), (0x1CB6, 'M', 'ჶ'), (0x1CB7, 'M', 'ჷ'), (0x1CB8, 'M', 'ჸ'), (0x1CB9, 'M', 'ჹ'), (0x1CBA, 'M', 'ჺ'), (0x1CBB, 'X'), (0x1CBD, 'M', 'ჽ'), (0x1CBE, 'M', 'ჾ'), (0x1CBF, 'M', 'ჿ'), (0x1CC0, 'V'), (0x1CC8, 'X'), (0x1CD0, 'V'), (0x1CFB, 'X'), (0x1D00, 'V'), (0x1D2C, 'M', 'a'), (0x1D2D, 'M', 'æ'), (0x1D2E, 'M', 'b'), (0x1D2F, 'V'), (0x1D30, 'M', 'd'), (0x1D31, 'M', 'e'), (0x1D32, 'M', 'ǝ'), (0x1D33, 'M', 'g'), (0x1D34, 'M', 'h'), (0x1D35, 'M', 'i'), (0x1D36, 'M', 'j'), (0x1D37, 'M', 'k'), (0x1D38, 'M', 'l'), (0x1D39, 'M', 'm'), (0x1D3A, 'M', 'n'), (0x1D3B, 'V'), (0x1D3C, 'M', 'o'), (0x1D3D, 'M', 'ȣ'), (0x1D3E, 'M', 'p'), (0x1D3F, 'M', 'r'), (0x1D40, 'M', 't'), (0x1D41, 'M', 'u'), (0x1D42, 'M', 'w'), (0x1D43, 'M', 'a'), (0x1D44, 'M', 'ɐ'), (0x1D45, 'M', 'ɑ'), (0x1D46, 'M', 'ᴂ'), (0x1D47, 'M', 'b'), (0x1D48, 'M', 'd'), (0x1D49, 'M', 'e'), (0x1D4A, 'M', 'ə'), (0x1D4B, 'M', 'ɛ'), (0x1D4C, 'M', 'ɜ'), (0x1D4D, 'M', 'g'), (0x1D4E, 'V'), (0x1D4F, 'M', 'k'), (0x1D50, 'M', 'm'), (0x1D51, 'M', 'ŋ'), (0x1D52, 'M', 'o'), (0x1D53, 'M', 'ɔ'), ] def _seg_16() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D54, 'M', 'ᴖ'), (0x1D55, 'M', 'ᴗ'), (0x1D56, 'M', 'p'), (0x1D57, 'M', 't'), (0x1D58, 'M', 'u'), (0x1D59, 'M', 'ᴝ'), (0x1D5A, 'M', 'ɯ'), (0x1D5B, 'M', 'v'), (0x1D5C, 'M', 'ᴥ'), (0x1D5D, 'M', 'β'), (0x1D5E, 'M', 'γ'), (0x1D5F, 'M', 'δ'), (0x1D60, 'M', 'φ'), (0x1D61, 'M', 'χ'), (0x1D62, 'M', 'i'), (0x1D63, 'M', 'r'), (0x1D64, 'M', 'u'), (0x1D65, 'M', 'v'), (0x1D66, 'M', 'β'), (0x1D67, 'M', 'γ'), (0x1D68, 'M', 'ρ'), (0x1D69, 'M', 'φ'), (0x1D6A, 'M', 'χ'), (0x1D6B, 'V'), (0x1D78, 'M', 'н'), (0x1D79, 'V'), (0x1D9B, 'M', 'ɒ'), (0x1D9C, 'M', 'c'), (0x1D9D, 'M', 'ɕ'), (0x1D9E, 'M', 'ð'), (0x1D9F, 'M', 'ɜ'), (0x1DA0, 'M', 'f'), (0x1DA1, 'M', 'ɟ'), (0x1DA2, 'M', 'ɡ'), (0x1DA3, 'M', 'ɥ'), (0x1DA4, 'M', 'ɨ'), (0x1DA5, 'M', 'ɩ'), (0x1DA6, 'M', 'ɪ'), (0x1DA7, 'M', 'ᵻ'), (0x1DA8, 'M', 'ʝ'), (0x1DA9, 'M', 'ɭ'), (0x1DAA, 'M', 'ᶅ'), (0x1DAB, 'M', 'ʟ'), (0x1DAC, 'M', 'ɱ'), (0x1DAD, 'M', 'ɰ'), (0x1DAE, 'M', 'ɲ'), (0x1DAF, 'M', 'ɳ'), (0x1DB0, 'M', 'ɴ'), (0x1DB1, 'M', 'ɵ'), (0x1DB2, 'M', 'ɸ'), (0x1DB3, 'M', 'ʂ'), (0x1DB4, 'M', 'ʃ'), (0x1DB5, 'M', 'ƫ'), (0x1DB6, 'M', 'ʉ'), (0x1DB7, 'M', 'ʊ'), (0x1DB8, 'M', 'ᴜ'), (0x1DB9, 'M', 'ʋ'), (0x1DBA, 'M', 'ʌ'), (0x1DBB, 'M', 'z'), (0x1DBC, 'M', 'ʐ'), (0x1DBD, 'M', 'ʑ'), (0x1DBE, 'M', 'ʒ'), (0x1DBF, 'M', 'θ'), (0x1DC0, 'V'), (0x1E00, 'M', 'ḁ'), (0x1E01, 'V'), (0x1E02, 'M', 'ḃ'), (0x1E03, 'V'), (0x1E04, 'M', 'ḅ'), (0x1E05, 'V'), (0x1E06, 'M', 'ḇ'), (0x1E07, 'V'), (0x1E08, 'M', 'ḉ'), (0x1E09, 'V'), (0x1E0A, 'M', 'ḋ'), (0x1E0B, 'V'), (0x1E0C, 'M', 'ḍ'), (0x1E0D, 'V'), (0x1E0E, 'M', 'ḏ'), (0x1E0F, 'V'), (0x1E10, 'M', 'ḑ'), (0x1E11, 'V'), (0x1E12, 'M', 'ḓ'), (0x1E13, 'V'), (0x1E14, 'M', 'ḕ'), (0x1E15, 'V'), (0x1E16, 'M', 'ḗ'), (0x1E17, 'V'), (0x1E18, 'M', 'ḙ'), (0x1E19, 'V'), (0x1E1A, 'M', 'ḛ'), (0x1E1B, 'V'), (0x1E1C, 'M', 'ḝ'), (0x1E1D, 'V'), (0x1E1E, 'M', 'ḟ'), (0x1E1F, 'V'), (0x1E20, 'M', 'ḡ'), (0x1E21, 'V'), (0x1E22, 'M', 'ḣ'), (0x1E23, 'V'), ] def _seg_17() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1E24, 'M', 'ḥ'), (0x1E25, 'V'), (0x1E26, 'M', 'ḧ'), (0x1E27, 'V'), (0x1E28, 'M', 'ḩ'), (0x1E29, 'V'), (0x1E2A, 'M', 'ḫ'), (0x1E2B, 'V'), (0x1E2C, 'M', 'ḭ'), (0x1E2D, 'V'), (0x1E2E, 'M', 'ḯ'), (0x1E2F, 'V'), (0x1E30, 'M', 'ḱ'), (0x1E31, 'V'), (0x1E32, 'M', 'ḳ'), (0x1E33, 'V'), (0x1E34, 'M', 'ḵ'), (0x1E35, 'V'), (0x1E36, 'M', 'ḷ'), (0x1E37, 'V'), (0x1E38, 'M', 'ḹ'), (0x1E39, 'V'), (0x1E3A, 'M', 'ḻ'), (0x1E3B, 'V'), (0x1E3C, 'M', 'ḽ'), (0x1E3D, 'V'), (0x1E3E, 'M', 'ḿ'), (0x1E3F, 'V'), (0x1E40, 'M', 'ṁ'), (0x1E41, 'V'), (0x1E42, 'M', 'ṃ'), (0x1E43, 'V'), (0x1E44, 'M', 'ṅ'), (0x1E45, 'V'), (0x1E46, 'M', 'ṇ'), (0x1E47, 'V'), (0x1E48, 'M', 'ṉ'), (0x1E49, 'V'), (0x1E4A, 'M', 'ṋ'), (0x1E4B, 'V'), (0x1E4C, 'M', 'ṍ'), (0x1E4D, 'V'), (0x1E4E, 'M', 'ṏ'), (0x1E4F, 'V'), (0x1E50, 'M', 'ṑ'), (0x1E51, 'V'), (0x1E52, 'M', 'ṓ'), (0x1E53, 'V'), (0x1E54, 'M', 'ṕ'), (0x1E55, 'V'), (0x1E56, 'M', 'ṗ'), (0x1E57, 'V'), (0x1E58, 'M', 'ṙ'), (0x1E59, 'V'), (0x1E5A, 'M', 'ṛ'), (0x1E5B, 'V'), (0x1E5C, 'M', 'ṝ'), (0x1E5D, 'V'), (0x1E5E, 'M', 'ṟ'), (0x1E5F, 'V'), (0x1E60, 'M', 'ṡ'), (0x1E61, 'V'), (0x1E62, 'M', 'ṣ'), (0x1E63, 'V'), (0x1E64, 'M', 'ṥ'), (0x1E65, 'V'), (0x1E66, 'M', 'ṧ'), (0x1E67, 'V'), (0x1E68, 'M', 'ṩ'), (0x1E69, 'V'), (0x1E6A, 'M', 'ṫ'), (0x1E6B, 'V'), (0x1E6C, 'M', 'ṭ'), (0x1E6D, 'V'), (0x1E6E, 'M', 'ṯ'), (0x1E6F, 'V'), (0x1E70, 'M', 'ṱ'), (0x1E71, 'V'), (0x1E72, 'M', 'ṳ'), (0x1E73, 'V'), (0x1E74, 'M', 'ṵ'), (0x1E75, 'V'), (0x1E76, 'M', 'ṷ'), (0x1E77, 'V'), (0x1E78, 'M', 'ṹ'), (0x1E79, 'V'), (0x1E7A, 'M', 'ṻ'), (0x1E7B, 'V'), (0x1E7C, 'M', 'ṽ'), (0x1E7D, 'V'), (0x1E7E, 'M', 'ṿ'), (0x1E7F, 'V'), (0x1E80, 'M', 'ẁ'), (0x1E81, 'V'), (0x1E82, 'M', 'ẃ'), (0x1E83, 'V'), (0x1E84, 'M', 'ẅ'), (0x1E85, 'V'), (0x1E86, 'M', 'ẇ'), (0x1E87, 'V'), ] def _seg_18() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1E88, 'M', 'ẉ'), (0x1E89, 'V'), (0x1E8A, 'M', 'ẋ'), (0x1E8B, 'V'), (0x1E8C, 'M', 'ẍ'), (0x1E8D, 'V'), (0x1E8E, 'M', 'ẏ'), (0x1E8F, 'V'), (0x1E90, 'M', 'ẑ'), (0x1E91, 'V'), (0x1E92, 'M', 'ẓ'), (0x1E93, 'V'), (0x1E94, 'M', 'ẕ'), (0x1E95, 'V'), (0x1E9A, 'M', 'aʾ'), (0x1E9B, 'M', 'ṡ'), (0x1E9C, 'V'), (0x1E9E, 'M', 'ss'), (0x1E9F, 'V'), (0x1EA0, 'M', 'ạ'), (0x1EA1, 'V'), (0x1EA2, 'M', 'ả'), (0x1EA3, 'V'), (0x1EA4, 'M', 'ấ'), (0x1EA5, 'V'), (0x1EA6, 'M', 'ầ'), (0x1EA7, 'V'), (0x1EA8, 'M', 'ẩ'), (0x1EA9, 'V'), (0x1EAA, 'M', 'ẫ'), (0x1EAB, 'V'), (0x1EAC, 'M', 'ậ'), (0x1EAD, 'V'), (0x1EAE, 'M', 'ắ'), (0x1EAF, 'V'), (0x1EB0, 'M', 'ằ'), (0x1EB1, 'V'), (0x1EB2, 'M', 'ẳ'), (0x1EB3, 'V'), (0x1EB4, 'M', 'ẵ'), (0x1EB5, 'V'), (0x1EB6, 'M', 'ặ'), (0x1EB7, 'V'), (0x1EB8, 'M', 'ẹ'), (0x1EB9, 'V'), (0x1EBA, 'M', 'ẻ'), (0x1EBB, 'V'), (0x1EBC, 'M', 'ẽ'), (0x1EBD, 'V'), (0x1EBE, 'M', 'ế'), (0x1EBF, 'V'), (0x1EC0, 'M', 'ề'), (0x1EC1, 'V'), (0x1EC2, 'M', 'ể'), (0x1EC3, 'V'), (0x1EC4, 'M', 'ễ'), (0x1EC5, 'V'), (0x1EC6, 'M', 'ệ'), (0x1EC7, 'V'), (0x1EC8, 'M', 'ỉ'), (0x1EC9, 'V'), (0x1ECA, 'M', 'ị'), (0x1ECB, 'V'), (0x1ECC, 'M', 'ọ'), (0x1ECD, 'V'), (0x1ECE, 'M', 'ỏ'), (0x1ECF, 'V'), (0x1ED0, 'M', 'ố'), (0x1ED1, 'V'), (0x1ED2, 'M', 'ồ'), (0x1ED3, 'V'), (0x1ED4, 'M', 'ổ'), (0x1ED5, 'V'), (0x1ED6, 'M', 'ỗ'), (0x1ED7, 'V'), (0x1ED8, 'M', 'ộ'), (0x1ED9, 'V'), (0x1EDA, 'M', 'ớ'), (0x1EDB, 'V'), (0x1EDC, 'M', 'ờ'), (0x1EDD, 'V'), (0x1EDE, 'M', 'ở'), (0x1EDF, 'V'), (0x1EE0, 'M', 'ỡ'), (0x1EE1, 'V'), (0x1EE2, 'M', 'ợ'), (0x1EE3, 'V'), (0x1EE4, 'M', 'ụ'), (0x1EE5, 'V'), (0x1EE6, 'M', 'ủ'), (0x1EE7, 'V'), (0x1EE8, 'M', 'ứ'), (0x1EE9, 'V'), (0x1EEA, 'M', 'ừ'), (0x1EEB, 'V'), (0x1EEC, 'M', 'ử'), (0x1EED, 'V'), (0x1EEE, 'M', 'ữ'), (0x1EEF, 'V'), (0x1EF0, 'M', 'ự'), ] def _seg_19() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1EF1, 'V'), (0x1EF2, 'M', 'ỳ'), (0x1EF3, 'V'), (0x1EF4, 'M', 'ỵ'), (0x1EF5, 'V'), (0x1EF6, 'M', 'ỷ'), (0x1EF7, 'V'), (0x1EF8, 'M', 'ỹ'), (0x1EF9, 'V'), (0x1EFA, 'M', 'ỻ'), (0x1EFB, 'V'), (0x1EFC, 'M', 'ỽ'), (0x1EFD, 'V'), (0x1EFE, 'M', 'ỿ'), (0x1EFF, 'V'), (0x1F08, 'M', 'ἀ'), (0x1F09, 'M', 'ἁ'), (0x1F0A, 'M', 'ἂ'), (0x1F0B, 'M', 'ἃ'), (0x1F0C, 'M', 'ἄ'), (0x1F0D, 'M', 'ἅ'), (0x1F0E, 'M', 'ἆ'), (0x1F0F, 'M', 'ἇ'), (0x1F10, 'V'), (0x1F16, 'X'), (0x1F18, 'M', 'ἐ'), (0x1F19, 'M', 'ἑ'), (0x1F1A, 'M', 'ἒ'), (0x1F1B, 'M', 'ἓ'), (0x1F1C, 'M', 'ἔ'), (0x1F1D, 'M', 'ἕ'), (0x1F1E, 'X'), (0x1F20, 'V'), (0x1F28, 'M', 'ἠ'), (0x1F29, 'M', 'ἡ'), (0x1F2A, 'M', 'ἢ'), (0x1F2B, 'M', 'ἣ'), (0x1F2C, 'M', 'ἤ'), (0x1F2D, 'M', 'ἥ'), (0x1F2E, 'M', 'ἦ'), (0x1F2F, 'M', 'ἧ'), (0x1F30, 'V'), (0x1F38, 'M', 'ἰ'), (0x1F39, 'M', 'ἱ'), (0x1F3A, 'M', 'ἲ'), (0x1F3B, 'M', 'ἳ'), (0x1F3C, 'M', 'ἴ'), (0x1F3D, 'M', 'ἵ'), (0x1F3E, 'M', 'ἶ'), (0x1F3F, 'M', 'ἷ'), (0x1F40, 'V'), (0x1F46, 'X'), (0x1F48, 'M', 'ὀ'), (0x1F49, 'M', 'ὁ'), (0x1F4A, 'M', 'ὂ'), (0x1F4B, 'M', 'ὃ'), (0x1F4C, 'M', 'ὄ'), (0x1F4D, 'M', 'ὅ'), (0x1F4E, 'X'), (0x1F50, 'V'), (0x1F58, 'X'), (0x1F59, 'M', 'ὑ'), (0x1F5A, 'X'), (0x1F5B, 'M', 'ὓ'), (0x1F5C, 'X'), (0x1F5D, 'M', 'ὕ'), (0x1F5E, 'X'), (0x1F5F, 'M', 'ὗ'), (0x1F60, 'V'), (0x1F68, 'M', 'ὠ'), (0x1F69, 'M', 'ὡ'), (0x1F6A, 'M', 'ὢ'), (0x1F6B, 'M', 'ὣ'), (0x1F6C, 'M', 'ὤ'), (0x1F6D, 'M', 'ὥ'), (0x1F6E, 'M', 'ὦ'), (0x1F6F, 'M', 'ὧ'), (0x1F70, 'V'), (0x1F71, 'M', 'ά'), (0x1F72, 'V'), (0x1F73, 'M', 'έ'), (0x1F74, 'V'), (0x1F75, 'M', 'ή'), (0x1F76, 'V'), (0x1F77, 'M', 'ί'), (0x1F78, 'V'), (0x1F79, 'M', 'ό'), (0x1F7A, 'V'), (0x1F7B, 'M', 'ύ'), (0x1F7C, 'V'), (0x1F7D, 'M', 'ώ'), (0x1F7E, 'X'), (0x1F80, 'M', 'ἀι'), (0x1F81, 'M', 'ἁι'), (0x1F82, 'M', 'ἂι'), (0x1F83, 'M', 'ἃι'), (0x1F84, 'M', 'ἄι'), (0x1F85, 'M', 'ἅι'), (0x1F86, 'M', 'ἆι'), (0x1F87, 'M', 'ἇι'), ] def _seg_20() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1F88, 'M', 'ἀι'), (0x1F89, 'M', 'ἁι'), (0x1F8A, 'M', 'ἂι'), (0x1F8B, 'M', 'ἃι'), (0x1F8C, 'M', 'ἄι'), (0x1F8D, 'M', 'ἅι'), (0x1F8E, 'M', 'ἆι'), (0x1F8F, 'M', 'ἇι'), (0x1F90, 'M', 'ἠι'), (0x1F91, 'M', 'ἡι'), (0x1F92, 'M', 'ἢι'), (0x1F93, 'M', 'ἣι'), (0x1F94, 'M', 'ἤι'), (0x1F95, 'M', 'ἥι'), (0x1F96, 'M', 'ἦι'), (0x1F97, 'M', 'ἧι'), (0x1F98, 'M', 'ἠι'), (0x1F99, 'M', 'ἡι'), (0x1F9A, 'M', 'ἢι'), (0x1F9B, 'M', 'ἣι'), (0x1F9C, 'M', 'ἤι'), (0x1F9D, 'M', 'ἥι'), (0x1F9E, 'M', 'ἦι'), (0x1F9F, 'M', 'ἧι'), (0x1FA0, 'M', 'ὠι'), (0x1FA1, 'M', 'ὡι'), (0x1FA2, 'M', 'ὢι'), (0x1FA3, 'M', 'ὣι'), (0x1FA4, 'M', 'ὤι'), (0x1FA5, 'M', 'ὥι'), (0x1FA6, 'M', 'ὦι'), (0x1FA7, 'M', 'ὧι'), (0x1FA8, 'M', 'ὠι'), (0x1FA9, 'M', 'ὡι'), (0x1FAA, 'M', 'ὢι'), (0x1FAB, 'M', 'ὣι'), (0x1FAC, 'M', 'ὤι'), (0x1FAD, 'M', 'ὥι'), (0x1FAE, 'M', 'ὦι'), (0x1FAF, 'M', 'ὧι'), (0x1FB0, 'V'), (0x1FB2, 'M', 'ὰι'), (0x1FB3, 'M', 'αι'), (0x1FB4, 'M', 'άι'), (0x1FB5, 'X'), (0x1FB6, 'V'), (0x1FB7, 'M', 'ᾶι'), (0x1FB8, 'M', 'ᾰ'), (0x1FB9, 'M', 'ᾱ'), (0x1FBA, 'M', 'ὰ'), (0x1FBB, 'M', 'ά'), (0x1FBC, 'M', 'αι'), (0x1FBD, '3', ' ̓'), (0x1FBE, 'M', 'ι'), (0x1FBF, '3', ' ̓'), (0x1FC0, '3', ' ͂'), (0x1FC1, '3', ' ̈͂'), (0x1FC2, 'M', 'ὴι'), (0x1FC3, 'M', 'ηι'), (0x1FC4, 'M', 'ήι'), (0x1FC5, 'X'), (0x1FC6, 'V'), (0x1FC7, 'M', 'ῆι'), (0x1FC8, 'M', 'ὲ'), (0x1FC9, 'M', 'έ'), (0x1FCA, 'M', 'ὴ'), (0x1FCB, 'M', 'ή'), (0x1FCC, 'M', 'ηι'), (0x1FCD, '3', ' ̓̀'), (0x1FCE, '3', ' ̓́'), (0x1FCF, '3', ' ̓͂'), (0x1FD0, 'V'), (0x1FD3, 'M', 'ΐ'), (0x1FD4, 'X'), (0x1FD6, 'V'), (0x1FD8, 'M', 'ῐ'), (0x1FD9, 'M', 'ῑ'), (0x1FDA, 'M', 'ὶ'), (0x1FDB, 'M', 'ί'), (0x1FDC, 'X'), (0x1FDD, '3', ' ̔̀'), (0x1FDE, '3', ' ̔́'), (0x1FDF, '3', ' ̔͂'), (0x1FE0, 'V'), (0x1FE3, 'M', 'ΰ'), (0x1FE4, 'V'), (0x1FE8, 'M', 'ῠ'), (0x1FE9, 'M', 'ῡ'), (0x1FEA, 'M', 'ὺ'), (0x1FEB, 'M', 'ύ'), (0x1FEC, 'M', 'ῥ'), (0x1FED, '3', ' ̈̀'), (0x1FEE, '3', ' ̈́'), (0x1FEF, '3', '`'), (0x1FF0, 'X'), (0x1FF2, 'M', 'ὼι'), (0x1FF3, 'M', 'ωι'), (0x1FF4, 'M', 'ώι'), (0x1FF5, 'X'), (0x1FF6, 'V'), ] def _seg_21() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1FF7, 'M', 'ῶι'), (0x1FF8, 'M', 'ὸ'), (0x1FF9, 'M', 'ό'), (0x1FFA, 'M', 'ὼ'), (0x1FFB, 'M', 'ώ'), (0x1FFC, 'M', 'ωι'), (0x1FFD, '3', ' ́'), (0x1FFE, '3', ' ̔'), (0x1FFF, 'X'), (0x2000, '3', ' '), (0x200B, 'I'), (0x200C, 'D', ''), (0x200E, 'X'), (0x2010, 'V'), (0x2011, 'M', '‐'), (0x2012, 'V'), (0x2017, '3', ' ̳'), (0x2018, 'V'), (0x2024, 'X'), (0x2027, 'V'), (0x2028, 'X'), (0x202F, '3', ' '), (0x2030, 'V'), (0x2033, 'M', '′′'), (0x2034, 'M', '′′′'), (0x2035, 'V'), (0x2036, 'M', '‵‵'), (0x2037, 'M', '‵‵‵'), (0x2038, 'V'), (0x203C, '3', '!!'), (0x203D, 'V'), (0x203E, '3', ' ̅'), (0x203F, 'V'), (0x2047, '3', '??'), (0x2048, '3', '?!'), (0x2049, '3', '!?'), (0x204A, 'V'), (0x2057, 'M', '′′′′'), (0x2058, 'V'), (0x205F, '3', ' '), (0x2060, 'I'), (0x2061, 'X'), (0x2064, 'I'), (0x2065, 'X'), (0x2070, 'M', '0'), (0x2071, 'M', 'i'), (0x2072, 'X'), (0x2074, 'M', '4'), (0x2075, 'M', '5'), (0x2076, 'M', '6'), (0x2077, 'M', '7'), (0x2078, 'M', '8'), (0x2079, 'M', '9'), (0x207A, '3', '+'), (0x207B, 'M', '−'), (0x207C, '3', '='), (0x207D, '3', '('), (0x207E, '3', ')'), (0x207F, 'M', 'n'), (0x2080, 'M', '0'), (0x2081, 'M', '1'), (0x2082, 'M', '2'), (0x2083, 'M', '3'), (0x2084, 'M', '4'), (0x2085, 'M', '5'), (0x2086, 'M', '6'), (0x2087, 'M', '7'), (0x2088, 'M', '8'), (0x2089, 'M', '9'), (0x208A, '3', '+'), (0x208B, 'M', '−'), (0x208C, '3', '='), (0x208D, '3', '('), (0x208E, '3', ')'), (0x208F, 'X'), (0x2090, 'M', 'a'), (0x2091, 'M', 'e'), (0x2092, 'M', 'o'), (0x2093, 'M', 'x'), (0x2094, 'M', 'ə'), (0x2095, 'M', 'h'), (0x2096, 'M', 'k'), (0x2097, 'M', 'l'), (0x2098, 'M', 'm'), (0x2099, 'M', 'n'), (0x209A, 'M', 'p'), (0x209B, 'M', 's'), (0x209C, 'M', 't'), (0x209D, 'X'), (0x20A0, 'V'), (0x20A8, 'M', 'rs'), (0x20A9, 'V'), (0x20C1, 'X'), (0x20D0, 'V'), (0x20F1, 'X'), (0x2100, '3', 'a/c'), (0x2101, '3', 'a/s'), (0x2102, 'M', 'c'), (0x2103, 'M', '°c'), (0x2104, 'V'), ] def _seg_22() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2105, '3', 'c/o'), (0x2106, '3', 'c/u'), (0x2107, 'M', 'ɛ'), (0x2108, 'V'), (0x2109, 'M', '°f'), (0x210A, 'M', 'g'), (0x210B, 'M', 'h'), (0x210F, 'M', 'ħ'), (0x2110, 'M', 'i'), (0x2112, 'M', 'l'), (0x2114, 'V'), (0x2115, 'M', 'n'), (0x2116, 'M', 'no'), (0x2117, 'V'), (0x2119, 'M', 'p'), (0x211A, 'M', 'q'), (0x211B, 'M', 'r'), (0x211E, 'V'), (0x2120, 'M', 'sm'), (0x2121, 'M', 'tel'), (0x2122, 'M', 'tm'), (0x2123, 'V'), (0x2124, 'M', 'z'), (0x2125, 'V'), (0x2126, 'M', 'ω'), (0x2127, 'V'), (0x2128, 'M', 'z'), (0x2129, 'V'), (0x212A, 'M', 'k'), (0x212B, 'M', 'å'), (0x212C, 'M', 'b'), (0x212D, 'M', 'c'), (0x212E, 'V'), (0x212F, 'M', 'e'), (0x2131, 'M', 'f'), (0x2132, 'X'), (0x2133, 'M', 'm'), (0x2134, 'M', 'o'), (0x2135, 'M', 'א'), (0x2136, 'M', 'ב'), (0x2137, 'M', 'ג'), (0x2138, 'M', 'ד'), (0x2139, 'M', 'i'), (0x213A, 'V'), (0x213B, 'M', 'fax'), (0x213C, 'M', 'π'), (0x213D, 'M', 'γ'), (0x213F, 'M', 'π'), (0x2140, 'M', '∑'), (0x2141, 'V'), (0x2145, 'M', 'd'), (0x2147, 'M', 'e'), (0x2148, 'M', 'i'), (0x2149, 'M', 'j'), (0x214A, 'V'), (0x2150, 'M', '1⁄7'), (0x2151, 'M', '1⁄9'), (0x2152, 'M', '1⁄10'), (0x2153, 'M', '1⁄3'), (0x2154, 'M', '2⁄3'), (0x2155, 'M', '1⁄5'), (0x2156, 'M', '2⁄5'), (0x2157, 'M', '3⁄5'), (0x2158, 'M', '4⁄5'), (0x2159, 'M', '1⁄6'), (0x215A, 'M', '5⁄6'), (0x215B, 'M', '1⁄8'), (0x215C, 'M', '3⁄8'), (0x215D, 'M', '5⁄8'), (0x215E, 'M', '7⁄8'), (0x215F, 'M', '1⁄'), (0x2160, 'M', 'i'), (0x2161, 'M', 'ii'), (0x2162, 'M', 'iii'), (0x2163, 'M', 'iv'), (0x2164, 'M', 'v'), (0x2165, 'M', 'vi'), (0x2166, 'M', 'vii'), (0x2167, 'M', 'viii'), (0x2168, 'M', 'ix'), (0x2169, 'M', 'x'), (0x216A, 'M', 'xi'), (0x216B, 'M', 'xii'), (0x216C, 'M', 'l'), (0x216D, 'M', 'c'), (0x216E, 'M', 'd'), (0x216F, 'M', 'm'), (0x2170, 'M', 'i'), (0x2171, 'M', 'ii'), (0x2172, 'M', 'iii'), (0x2173, 'M', 'iv'), (0x2174, 'M', 'v'), (0x2175, 'M', 'vi'), (0x2176, 'M', 'vii'), (0x2177, 'M', 'viii'), (0x2178, 'M', 'ix'), (0x2179, 'M', 'x'), (0x217A, 'M', 'xi'), (0x217B, 'M', 'xii'), (0x217C, 'M', 'l'), ] def _seg_23() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x217D, 'M', 'c'), (0x217E, 'M', 'd'), (0x217F, 'M', 'm'), (0x2180, 'V'), (0x2183, 'X'), (0x2184, 'V'), (0x2189, 'M', '0⁄3'), (0x218A, 'V'), (0x218C, 'X'), (0x2190, 'V'), (0x222C, 'M', '∫∫'), (0x222D, 'M', '∫∫∫'), (0x222E, 'V'), (0x222F, 'M', '∮∮'), (0x2230, 'M', '∮∮∮'), (0x2231, 'V'), (0x2260, '3'), (0x2261, 'V'), (0x226E, '3'), (0x2270, 'V'), (0x2329, 'M', '〈'), (0x232A, 'M', '〉'), (0x232B, 'V'), (0x2427, 'X'), (0x2440, 'V'), (0x244B, 'X'), (0x2460, 'M', '1'), (0x2461, 'M', '2'), (0x2462, 'M', '3'), (0x2463, 'M', '4'), (0x2464, 'M', '5'), (0x2465, 'M', '6'), (0x2466, 'M', '7'), (0x2467, 'M', '8'), (0x2468, 'M', '9'), (0x2469, 'M', '10'), (0x246A, 'M', '11'), (0x246B, 'M', '12'), (0x246C, 'M', '13'), (0x246D, 'M', '14'), (0x246E, 'M', '15'), (0x246F, 'M', '16'), (0x2470, 'M', '17'), (0x2471, 'M', '18'), (0x2472, 'M', '19'), (0x2473, 'M', '20'), (0x2474, '3', '(1)'), (0x2475, '3', '(2)'), (0x2476, '3', '(3)'), (0x2477, '3', '(4)'), (0x2478, '3', '(5)'), (0x2479, '3', '(6)'), (0x247A, '3', '(7)'), (0x247B, '3', '(8)'), (0x247C, '3', '(9)'), (0x247D, '3', '(10)'), (0x247E, '3', '(11)'), (0x247F, '3', '(12)'), (0x2480, '3', '(13)'), (0x2481, '3', '(14)'), (0x2482, '3', '(15)'), (0x2483, '3', '(16)'), (0x2484, '3', '(17)'), (0x2485, '3', '(18)'), (0x2486, '3', '(19)'), (0x2487, '3', '(20)'), (0x2488, 'X'), (0x249C, '3', '(a)'), (0x249D, '3', '(b)'), (0x249E, '3', '(c)'), (0x249F, '3', '(d)'), (0x24A0, '3', '(e)'), (0x24A1, '3', '(f)'), (0x24A2, '3', '(g)'), (0x24A3, '3', '(h)'), (0x24A4, '3', '(i)'), (0x24A5, '3', '(j)'), (0x24A6, '3', '(k)'), (0x24A7, '3', '(l)'), (0x24A8, '3', '(m)'), (0x24A9, '3', '(n)'), (0x24AA, '3', '(o)'), (0x24AB, '3', '(p)'), (0x24AC, '3', '(q)'), (0x24AD, '3', '(r)'), (0x24AE, '3', '(s)'), (0x24AF, '3', '(t)'), (0x24B0, '3', '(u)'), (0x24B1, '3', '(v)'), (0x24B2, '3', '(w)'), (0x24B3, '3', '(x)'), (0x24B4, '3', '(y)'), (0x24B5, '3', '(z)'), (0x24B6, 'M', 'a'), (0x24B7, 'M', 'b'), (0x24B8, 'M', 'c'), (0x24B9, 'M', 'd'), (0x24BA, 'M', 'e'), (0x24BB, 'M', 'f'), (0x24BC, 'M', 'g'), ] def _seg_24() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x24BD, 'M', 'h'), (0x24BE, 'M', 'i'), (0x24BF, 'M', 'j'), (0x24C0, 'M', 'k'), (0x24C1, 'M', 'l'), (0x24C2, 'M', 'm'), (0x24C3, 'M', 'n'), (0x24C4, 'M', 'o'), (0x24C5, 'M', 'p'), (0x24C6, 'M', 'q'), (0x24C7, 'M', 'r'), (0x24C8, 'M', 's'), (0x24C9, 'M', 't'), (0x24CA, 'M', 'u'), (0x24CB, 'M', 'v'), (0x24CC, 'M', 'w'), (0x24CD, 'M', 'x'), (0x24CE, 'M', 'y'), (0x24CF, 'M', 'z'), (0x24D0, 'M', 'a'), (0x24D1, 'M', 'b'), (0x24D2, 'M', 'c'), (0x24D3, 'M', 'd'), (0x24D4, 'M', 'e'), (0x24D5, 'M', 'f'), (0x24D6, 'M', 'g'), (0x24D7, 'M', 'h'), (0x24D8, 'M', 'i'), (0x24D9, 'M', 'j'), (0x24DA, 'M', 'k'), (0x24DB, 'M', 'l'), (0x24DC, 'M', 'm'), (0x24DD, 'M', 'n'), (0x24DE, 'M', 'o'), (0x24DF, 'M', 'p'), (0x24E0, 'M', 'q'), (0x24E1, 'M', 'r'), (0x24E2, 'M', 's'), (0x24E3, 'M', 't'), (0x24E4, 'M', 'u'), (0x24E5, 'M', 'v'), (0x24E6, 'M', 'w'), (0x24E7, 'M', 'x'), (0x24E8, 'M', 'y'), (0x24E9, 'M', 'z'), (0x24EA, 'M', '0'), (0x24EB, 'V'), (0x2A0C, 'M', '∫∫∫∫'), (0x2A0D, 'V'), (0x2A74, '3', '::='), (0x2A75, '3', '=='), (0x2A76, '3', '==='), (0x2A77, 'V'), (0x2ADC, 'M', '⫝̸'), (0x2ADD, 'V'), (0x2B74, 'X'), (0x2B76, 'V'), (0x2B96, 'X'), (0x2B97, 'V'), (0x2C00, 'M', 'ⰰ'), (0x2C01, 'M', 'ⰱ'), (0x2C02, 'M', 'ⰲ'), (0x2C03, 'M', 'ⰳ'), (0x2C04, 'M', 'ⰴ'), (0x2C05, 'M', 'ⰵ'), (0x2C06, 'M', 'ⰶ'), (0x2C07, 'M', 'ⰷ'), (0x2C08, 'M', 'ⰸ'), (0x2C09, 'M', 'ⰹ'), (0x2C0A, 'M', 'ⰺ'), (0x2C0B, 'M', 'ⰻ'), (0x2C0C, 'M', 'ⰼ'), (0x2C0D, 'M', 'ⰽ'), (0x2C0E, 'M', 'ⰾ'), (0x2C0F, 'M', 'ⰿ'), (0x2C10, 'M', 'ⱀ'), (0x2C11, 'M', 'ⱁ'), (0x2C12, 'M', 'ⱂ'), (0x2C13, 'M', 'ⱃ'), (0x2C14, 'M', 'ⱄ'), (0x2C15, 'M', 'ⱅ'), (0x2C16, 'M', 'ⱆ'), (0x2C17, 'M', 'ⱇ'), (0x2C18, 'M', 'ⱈ'), (0x2C19, 'M', 'ⱉ'), (0x2C1A, 'M', 'ⱊ'), (0x2C1B, 'M', 'ⱋ'), (0x2C1C, 'M', 'ⱌ'), (0x2C1D, 'M', 'ⱍ'), (0x2C1E, 'M', 'ⱎ'), (0x2C1F, 'M', 'ⱏ'), (0x2C20, 'M', 'ⱐ'), (0x2C21, 'M', 'ⱑ'), (0x2C22, 'M', 'ⱒ'), (0x2C23, 'M', 'ⱓ'), (0x2C24, 'M', 'ⱔ'), (0x2C25, 'M', 'ⱕ'), (0x2C26, 'M', 'ⱖ'), (0x2C27, 'M', 'ⱗ'), (0x2C28, 'M', 'ⱘ'), ] def _seg_25() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2C29, 'M', 'ⱙ'), (0x2C2A, 'M', 'ⱚ'), (0x2C2B, 'M', 'ⱛ'), (0x2C2C, 'M', 'ⱜ'), (0x2C2D, 'M', 'ⱝ'), (0x2C2E, 'M', 'ⱞ'), (0x2C2F, 'M', 'ⱟ'), (0x2C30, 'V'), (0x2C60, 'M', 'ⱡ'), (0x2C61, 'V'), (0x2C62, 'M', 'ɫ'), (0x2C63, 'M', 'ᵽ'), (0x2C64, 'M', 'ɽ'), (0x2C65, 'V'), (0x2C67, 'M', 'ⱨ'), (0x2C68, 'V'), (0x2C69, 'M', 'ⱪ'), (0x2C6A, 'V'), (0x2C6B, 'M', 'ⱬ'), (0x2C6C, 'V'), (0x2C6D, 'M', 'ɑ'), (0x2C6E, 'M', 'ɱ'), (0x2C6F, 'M', 'ɐ'), (0x2C70, 'M', 'ɒ'), (0x2C71, 'V'), (0x2C72, 'M', 'ⱳ'), (0x2C73, 'V'), (0x2C75, 'M', 'ⱶ'), (0x2C76, 'V'), (0x2C7C, 'M', 'j'), (0x2C7D, 'M', 'v'), (0x2C7E, 'M', 'ȿ'), (0x2C7F, 'M', 'ɀ'), (0x2C80, 'M', 'ⲁ'), (0x2C81, 'V'), (0x2C82, 'M', 'ⲃ'), (0x2C83, 'V'), (0x2C84, 'M', 'ⲅ'), (0x2C85, 'V'), (0x2C86, 'M', 'ⲇ'), (0x2C87, 'V'), (0x2C88, 'M', 'ⲉ'), (0x2C89, 'V'), (0x2C8A, 'M', 'ⲋ'), (0x2C8B, 'V'), (0x2C8C, 'M', 'ⲍ'), (0x2C8D, 'V'), (0x2C8E, 'M', 'ⲏ'), (0x2C8F, 'V'), (0x2C90, 'M', 'ⲑ'), (0x2C91, 'V'), (0x2C92, 'M', 'ⲓ'), (0x2C93, 'V'), (0x2C94, 'M', 'ⲕ'), (0x2C95, 'V'), (0x2C96, 'M', 'ⲗ'), (0x2C97, 'V'), (0x2C98, 'M', 'ⲙ'), (0x2C99, 'V'), (0x2C9A, 'M', 'ⲛ'), (0x2C9B, 'V'), (0x2C9C, 'M', 'ⲝ'), (0x2C9D, 'V'), (0x2C9E, 'M', 'ⲟ'), (0x2C9F, 'V'), (0x2CA0, 'M', 'ⲡ'), (0x2CA1, 'V'), (0x2CA2, 'M', 'ⲣ'), (0x2CA3, 'V'), (0x2CA4, 'M', 'ⲥ'), (0x2CA5, 'V'), (0x2CA6, 'M', 'ⲧ'), (0x2CA7, 'V'), (0x2CA8, 'M', 'ⲩ'), (0x2CA9, 'V'), (0x2CAA, 'M', 'ⲫ'), (0x2CAB, 'V'), (0x2CAC, 'M', 'ⲭ'), (0x2CAD, 'V'), (0x2CAE, 'M', 'ⲯ'), (0x2CAF, 'V'), (0x2CB0, 'M', 'ⲱ'), (0x2CB1, 'V'), (0x2CB2, 'M', 'ⲳ'), (0x2CB3, 'V'), (0x2CB4, 'M', 'ⲵ'), (0x2CB5, 'V'), (0x2CB6, 'M', 'ⲷ'), (0x2CB7, 'V'), (0x2CB8, 'M', 'ⲹ'), (0x2CB9, 'V'), (0x2CBA, 'M', 'ⲻ'), (0x2CBB, 'V'), (0x2CBC, 'M', 'ⲽ'), (0x2CBD, 'V'), (0x2CBE, 'M', 'ⲿ'), (0x2CBF, 'V'), (0x2CC0, 'M', 'ⳁ'), (0x2CC1, 'V'), (0x2CC2, 'M', 'ⳃ'), ] def _seg_26() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2CC3, 'V'), (0x2CC4, 'M', 'ⳅ'), (0x2CC5, 'V'), (0x2CC6, 'M', 'ⳇ'), (0x2CC7, 'V'), (0x2CC8, 'M', 'ⳉ'), (0x2CC9, 'V'), (0x2CCA, 'M', 'ⳋ'), (0x2CCB, 'V'), (0x2CCC, 'M', 'ⳍ'), (0x2CCD, 'V'), (0x2CCE, 'M', 'ⳏ'), (0x2CCF, 'V'), (0x2CD0, 'M', 'ⳑ'), (0x2CD1, 'V'), (0x2CD2, 'M', 'ⳓ'), (0x2CD3, 'V'), (0x2CD4, 'M', 'ⳕ'), (0x2CD5, 'V'), (0x2CD6, 'M', 'ⳗ'), (0x2CD7, 'V'), (0x2CD8, 'M', 'ⳙ'), (0x2CD9, 'V'), (0x2CDA, 'M', 'ⳛ'), (0x2CDB, 'V'), (0x2CDC, 'M', 'ⳝ'), (0x2CDD, 'V'), (0x2CDE, 'M', 'ⳟ'), (0x2CDF, 'V'), (0x2CE0, 'M', 'ⳡ'), (0x2CE1, 'V'), (0x2CE2, 'M', 'ⳣ'), (0x2CE3, 'V'), (0x2CEB, 'M', 'ⳬ'), (0x2CEC, 'V'), (0x2CED, 'M', 'ⳮ'), (0x2CEE, 'V'), (0x2CF2, 'M', 'ⳳ'), (0x2CF3, 'V'), (0x2CF4, 'X'), (0x2CF9, 'V'), (0x2D26, 'X'), (0x2D27, 'V'), (0x2D28, 'X'), (0x2D2D, 'V'), (0x2D2E, 'X'), (0x2D30, 'V'), (0x2D68, 'X'), (0x2D6F, 'M', 'ⵡ'), (0x2D70, 'V'), (0x2D71, 'X'), (0x2D7F, 'V'), (0x2D97, 'X'), (0x2DA0, 'V'), (0x2DA7, 'X'), (0x2DA8, 'V'), (0x2DAF, 'X'), (0x2DB0, 'V'), (0x2DB7, 'X'), (0x2DB8, 'V'), (0x2DBF, 'X'), (0x2DC0, 'V'), (0x2DC7, 'X'), (0x2DC8, 'V'), (0x2DCF, 'X'), (0x2DD0, 'V'), (0x2DD7, 'X'), (0x2DD8, 'V'), (0x2DDF, 'X'), (0x2DE0, 'V'), (0x2E5E, 'X'), (0x2E80, 'V'), (0x2E9A, 'X'), (0x2E9B, 'V'), (0x2E9F, 'M', '母'), (0x2EA0, 'V'), (0x2EF3, 'M', '龟'), (0x2EF4, 'X'), (0x2F00, 'M', '一'), (0x2F01, 'M', '丨'), (0x2F02, 'M', '丶'), (0x2F03, 'M', '丿'), (0x2F04, 'M', '乙'), (0x2F05, 'M', '亅'), (0x2F06, 'M', '二'), (0x2F07, 'M', '亠'), (0x2F08, 'M', '人'), (0x2F09, 'M', '儿'), (0x2F0A, 'M', '入'), (0x2F0B, 'M', '八'), (0x2F0C, 'M', '冂'), (0x2F0D, 'M', '冖'), (0x2F0E, 'M', '冫'), (0x2F0F, 'M', '几'), (0x2F10, 'M', '凵'), (0x2F11, 'M', '刀'), (0x2F12, 'M', '力'), (0x2F13, 'M', '勹'), (0x2F14, 'M', '匕'), (0x2F15, 'M', '匚'), ] def _seg_27() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F16, 'M', '匸'), (0x2F17, 'M', '十'), (0x2F18, 'M', '卜'), (0x2F19, 'M', '卩'), (0x2F1A, 'M', '厂'), (0x2F1B, 'M', '厶'), (0x2F1C, 'M', '又'), (0x2F1D, 'M', '口'), (0x2F1E, 'M', '囗'), (0x2F1F, 'M', '土'), (0x2F20, 'M', '士'), (0x2F21, 'M', '夂'), (0x2F22, 'M', '夊'), (0x2F23, 'M', '夕'), (0x2F24, 'M', '大'), (0x2F25, 'M', '女'), (0x2F26, 'M', '子'), (0x2F27, 'M', '宀'), (0x2F28, 'M', '寸'), (0x2F29, 'M', '小'), (0x2F2A, 'M', '尢'), (0x2F2B, 'M', '尸'), (0x2F2C, 'M', '屮'), (0x2F2D, 'M', '山'), (0x2F2E, 'M', '巛'), (0x2F2F, 'M', '工'), (0x2F30, 'M', '己'), (0x2F31, 'M', '巾'), (0x2F32, 'M', '干'), (0x2F33, 'M', '幺'), (0x2F34, 'M', '广'), (0x2F35, 'M', '廴'), (0x2F36, 'M', '廾'), (0x2F37, 'M', '弋'), (0x2F38, 'M', '弓'), (0x2F39, 'M', '彐'), (0x2F3A, 'M', '彡'), (0x2F3B, 'M', '彳'), (0x2F3C, 'M', '心'), (0x2F3D, 'M', '戈'), (0x2F3E, 'M', '戶'), (0x2F3F, 'M', '手'), (0x2F40, 'M', '支'), (0x2F41, 'M', '攴'), (0x2F42, 'M', '文'), (0x2F43, 'M', '斗'), (0x2F44, 'M', '斤'), (0x2F45, 'M', '方'), (0x2F46, 'M', '无'), (0x2F47, 'M', '日'), (0x2F48, 'M', '曰'), (0x2F49, 'M', '月'), (0x2F4A, 'M', '木'), (0x2F4B, 'M', '欠'), (0x2F4C, 'M', '止'), (0x2F4D, 'M', '歹'), (0x2F4E, 'M', '殳'), (0x2F4F, 'M', '毋'), (0x2F50, 'M', '比'), (0x2F51, 'M', '毛'), (0x2F52, 'M', '氏'), (0x2F53, 'M', '气'), (0x2F54, 'M', '水'), (0x2F55, 'M', '火'), (0x2F56, 'M', '爪'), (0x2F57, 'M', '父'), (0x2F58, 'M', '爻'), (0x2F59, 'M', '爿'), (0x2F5A, 'M', '片'), (0x2F5B, 'M', '牙'), (0x2F5C, 'M', '牛'), (0x2F5D, 'M', '犬'), (0x2F5E, 'M', '玄'), (0x2F5F, 'M', '玉'), (0x2F60, 'M', '瓜'), (0x2F61, 'M', '瓦'), (0x2F62, 'M', '甘'), (0x2F63, 'M', '生'), (0x2F64, 'M', '用'), (0x2F65, 'M', '田'), (0x2F66, 'M', '疋'), (0x2F67, 'M', '疒'), (0x2F68, 'M', '癶'), (0x2F69, 'M', '白'), (0x2F6A, 'M', '皮'), (0x2F6B, 'M', '皿'), (0x2F6C, 'M', '目'), (0x2F6D, 'M', '矛'), (0x2F6E, 'M', '矢'), (0x2F6F, 'M', '石'), (0x2F70, 'M', '示'), (0x2F71, 'M', '禸'), (0x2F72, 'M', '禾'), (0x2F73, 'M', '穴'), (0x2F74, 'M', '立'), (0x2F75, 'M', '竹'), (0x2F76, 'M', '米'), (0x2F77, 'M', '糸'), (0x2F78, 'M', '缶'), (0x2F79, 'M', '网'), ] def _seg_28() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F7A, 'M', '羊'), (0x2F7B, 'M', '羽'), (0x2F7C, 'M', '老'), (0x2F7D, 'M', '而'), (0x2F7E, 'M', '耒'), (0x2F7F, 'M', '耳'), (0x2F80, 'M', '聿'), (0x2F81, 'M', '肉'), (0x2F82, 'M', '臣'), (0x2F83, 'M', '自'), (0x2F84, 'M', '至'), (0x2F85, 'M', '臼'), (0x2F86, 'M', '舌'), (0x2F87, 'M', '舛'), (0x2F88, 'M', '舟'), (0x2F89, 'M', '艮'), (0x2F8A, 'M', '色'), (0x2F8B, 'M', '艸'), (0x2F8C, 'M', '虍'), (0x2F8D, 'M', '虫'), (0x2F8E, 'M', '血'), (0x2F8F, 'M', '行'), (0x2F90, 'M', '衣'), (0x2F91, 'M', '襾'), (0x2F92, 'M', '見'), (0x2F93, 'M', '角'), (0x2F94, 'M', '言'), (0x2F95, 'M', '谷'), (0x2F96, 'M', '豆'), (0x2F97, 'M', '豕'), (0x2F98, 'M', '豸'), (0x2F99, 'M', '貝'), (0x2F9A, 'M', '赤'), (0x2F9B, 'M', '走'), (0x2F9C, 'M', '足'), (0x2F9D, 'M', '身'), (0x2F9E, 'M', '車'), (0x2F9F, 'M', '辛'), (0x2FA0, 'M', '辰'), (0x2FA1, 'M', '辵'), (0x2FA2, 'M', '邑'), (0x2FA3, 'M', '酉'), (0x2FA4, 'M', '釆'), (0x2FA5, 'M', '里'), (0x2FA6, 'M', '金'), (0x2FA7, 'M', '長'), (0x2FA8, 'M', '門'), (0x2FA9, 'M', '阜'), (0x2FAA, 'M', '隶'), (0x2FAB, 'M', '隹'), (0x2FAC, 'M', '雨'), (0x2FAD, 'M', '靑'), (0x2FAE, 'M', '非'), (0x2FAF, 'M', '面'), (0x2FB0, 'M', '革'), (0x2FB1, 'M', '韋'), (0x2FB2, 'M', '韭'), (0x2FB3, 'M', '音'), (0x2FB4, 'M', '頁'), (0x2FB5, 'M', '風'), (0x2FB6, 'M', '飛'), (0x2FB7, 'M', '食'), (0x2FB8, 'M', '首'), (0x2FB9, 'M', '香'), (0x2FBA, 'M', '馬'), (0x2FBB, 'M', '骨'), (0x2FBC, 'M', '高'), (0x2FBD, 'M', '髟'), (0x2FBE, 'M', '鬥'), (0x2FBF, 'M', '鬯'), (0x2FC0, 'M', '鬲'), (0x2FC1, 'M', '鬼'), (0x2FC2, 'M', '魚'), (0x2FC3, 'M', '鳥'), (0x2FC4, 'M', '鹵'), (0x2FC5, 'M', '鹿'), (0x2FC6, 'M', '麥'), (0x2FC7, 'M', '麻'), (0x2FC8, 'M', '黃'), (0x2FC9, 'M', '黍'), (0x2FCA, 'M', '黑'), (0x2FCB, 'M', '黹'), (0x2FCC, 'M', '黽'), (0x2FCD, 'M', '鼎'), (0x2FCE, 'M', '鼓'), (0x2FCF, 'M', '鼠'), (0x2FD0, 'M', '鼻'), (0x2FD1, 'M', '齊'), (0x2FD2, 'M', '齒'), (0x2FD3, 'M', '龍'), (0x2FD4, 'M', '龜'), (0x2FD5, 'M', '龠'), (0x2FD6, 'X'), (0x3000, '3', ' '), (0x3001, 'V'), (0x3002, 'M', '.'), (0x3003, 'V'), (0x3036, 'M', '〒'), (0x3037, 'V'), (0x3038, 'M', '十'), ] def _seg_29() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3039, 'M', '卄'), (0x303A, 'M', '卅'), (0x303B, 'V'), (0x3040, 'X'), (0x3041, 'V'), (0x3097, 'X'), (0x3099, 'V'), (0x309B, '3', ' ゙'), (0x309C, '3', ' ゚'), (0x309D, 'V'), (0x309F, 'M', 'より'), (0x30A0, 'V'), (0x30FF, 'M', 'コト'), (0x3100, 'X'), (0x3105, 'V'), (0x3130, 'X'), (0x3131, 'M', 'ᄀ'), (0x3132, 'M', 'ᄁ'), (0x3133, 'M', 'ᆪ'), (0x3134, 'M', 'ᄂ'), (0x3135, 'M', 'ᆬ'), (0x3136, 'M', 'ᆭ'), (0x3137, 'M', 'ᄃ'), (0x3138, 'M', 'ᄄ'), (0x3139, 'M', 'ᄅ'), (0x313A, 'M', 'ᆰ'), (0x313B, 'M', 'ᆱ'), (0x313C, 'M', 'ᆲ'), (0x313D, 'M', 'ᆳ'), (0x313E, 'M', 'ᆴ'), (0x313F, 'M', 'ᆵ'), (0x3140, 'M', 'ᄚ'), (0x3141, 'M', 'ᄆ'), (0x3142, 'M', 'ᄇ'), (0x3143, 'M', 'ᄈ'), (0x3144, 'M', 'ᄡ'), (0x3145, 'M', 'ᄉ'), (0x3146, 'M', 'ᄊ'), (0x3147, 'M', 'ᄋ'), (0x3148, 'M', 'ᄌ'), (0x3149, 'M', 'ᄍ'), (0x314A, 'M', 'ᄎ'), (0x314B, 'M', 'ᄏ'), (0x314C, 'M', 'ᄐ'), (0x314D, 'M', 'ᄑ'), (0x314E, 'M', 'ᄒ'), (0x314F, 'M', 'ᅡ'), (0x3150, 'M', 'ᅢ'), (0x3151, 'M', 'ᅣ'), (0x3152, 'M', 'ᅤ'), (0x3153, 'M', 'ᅥ'), (0x3154, 'M', 'ᅦ'), (0x3155, 'M', 'ᅧ'), (0x3156, 'M', 'ᅨ'), (0x3157, 'M', 'ᅩ'), (0x3158, 'M', 'ᅪ'), (0x3159, 'M', 'ᅫ'), (0x315A, 'M', 'ᅬ'), (0x315B, 'M', 'ᅭ'), (0x315C, 'M', 'ᅮ'), (0x315D, 'M', 'ᅯ'), (0x315E, 'M', 'ᅰ'), (0x315F, 'M', 'ᅱ'), (0x3160, 'M', 'ᅲ'), (0x3161, 'M', 'ᅳ'), (0x3162, 'M', 'ᅴ'), (0x3163, 'M', 'ᅵ'), (0x3164, 'X'), (0x3165, 'M', 'ᄔ'), (0x3166, 'M', 'ᄕ'), (0x3167, 'M', 'ᇇ'), (0x3168, 'M', 'ᇈ'), (0x3169, 'M', 'ᇌ'), (0x316A, 'M', 'ᇎ'), (0x316B, 'M', 'ᇓ'), (0x316C, 'M', 'ᇗ'), (0x316D, 'M', 'ᇙ'), (0x316E, 'M', 'ᄜ'), (0x316F, 'M', 'ᇝ'), (0x3170, 'M', 'ᇟ'), (0x3171, 'M', 'ᄝ'), (0x3172, 'M', 'ᄞ'), (0x3173, 'M', 'ᄠ'), (0x3174, 'M', 'ᄢ'), (0x3175, 'M', 'ᄣ'), (0x3176, 'M', 'ᄧ'), (0x3177, 'M', 'ᄩ'), (0x3178, 'M', 'ᄫ'), (0x3179, 'M', 'ᄬ'), (0x317A, 'M', 'ᄭ'), (0x317B, 'M', 'ᄮ'), (0x317C, 'M', 'ᄯ'), (0x317D, 'M', 'ᄲ'), (0x317E, 'M', 'ᄶ'), (0x317F, 'M', 'ᅀ'), (0x3180, 'M', 'ᅇ'), (0x3181, 'M', 'ᅌ'), (0x3182, 'M', 'ᇱ'), (0x3183, 'M', 'ᇲ'), (0x3184, 'M', 'ᅗ'), ] def _seg_30() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3185, 'M', 'ᅘ'), (0x3186, 'M', 'ᅙ'), (0x3187, 'M', 'ᆄ'), (0x3188, 'M', 'ᆅ'), (0x3189, 'M', 'ᆈ'), (0x318A, 'M', 'ᆑ'), (0x318B, 'M', 'ᆒ'), (0x318C, 'M', 'ᆔ'), (0x318D, 'M', 'ᆞ'), (0x318E, 'M', 'ᆡ'), (0x318F, 'X'), (0x3190, 'V'), (0x3192, 'M', '一'), (0x3193, 'M', '二'), (0x3194, 'M', '三'), (0x3195, 'M', '四'), (0x3196, 'M', '上'), (0x3197, 'M', '中'), (0x3198, 'M', '下'), (0x3199, 'M', '甲'), (0x319A, 'M', '乙'), (0x319B, 'M', '丙'), (0x319C, 'M', '丁'), (0x319D, 'M', '天'), (0x319E, 'M', '地'), (0x319F, 'M', '人'), (0x31A0, 'V'), (0x31E4, 'X'), (0x31F0, 'V'), (0x3200, '3', '(ᄀ)'), (0x3201, '3', '(ᄂ)'), (0x3202, '3', '(ᄃ)'), (0x3203, '3', '(ᄅ)'), (0x3204, '3', '(ᄆ)'), (0x3205, '3', '(ᄇ)'), (0x3206, '3', '(ᄉ)'), (0x3207, '3', '(ᄋ)'), (0x3208, '3', '(ᄌ)'), (0x3209, '3', '(ᄎ)'), (0x320A, '3', '(ᄏ)'), (0x320B, '3', '(ᄐ)'), (0x320C, '3', '(ᄑ)'), (0x320D, '3', '(ᄒ)'), (0x320E, '3', '(가)'), (0x320F, '3', '(나)'), (0x3210, '3', '(다)'), (0x3211, '3', '(라)'), (0x3212, '3', '(마)'), (0x3213, '3', '(바)'), (0x3214, '3', '(사)'), (0x3215, '3', '(아)'), (0x3216, '3', '(자)'), (0x3217, '3', '(차)'), (0x3218, '3', '(카)'), (0x3219, '3', '(타)'), (0x321A, '3', '(파)'), (0x321B, '3', '(하)'), (0x321C, '3', '(주)'), (0x321D, '3', '(오전)'), (0x321E, '3', '(오후)'), (0x321F, 'X'), (0x3220, '3', '(一)'), (0x3221, '3', '(二)'), (0x3222, '3', '(三)'), (0x3223, '3', '(四)'), (0x3224, '3', '(五)'), (0x3225, '3', '(六)'), (0x3226, '3', '(七)'), (0x3227, '3', '(八)'), (0x3228, '3', '(九)'), (0x3229, '3', '(十)'), (0x322A, '3', '(月)'), (0x322B, '3', '(火)'), (0x322C, '3', '(水)'), (0x322D, '3', '(木)'), (0x322E, '3', '(金)'), (0x322F, '3', '(土)'), (0x3230, '3', '(日)'), (0x3231, '3', '(株)'), (0x3232, '3', '(有)'), (0x3233, '3', '(社)'), (0x3234, '3', '(名)'), (0x3235, '3', '(特)'), (0x3236, '3', '(財)'), (0x3237, '3', '(祝)'), (0x3238, '3', '(労)'), (0x3239, '3', '(代)'), (0x323A, '3', '(呼)'), (0x323B, '3', '(学)'), (0x323C, '3', '(監)'), (0x323D, '3', '(企)'), (0x323E, '3', '(資)'), (0x323F, '3', '(協)'), (0x3240, '3', '(祭)'), (0x3241, '3', '(休)'), (0x3242, '3', '(自)'), (0x3243, '3', '(至)'), (0x3244, 'M', '問'), (0x3245, 'M', '幼'), (0x3246, 'M', '文'), ] def _seg_31() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3247, 'M', '箏'), (0x3248, 'V'), (0x3250, 'M', 'pte'), (0x3251, 'M', '21'), (0x3252, 'M', '22'), (0x3253, 'M', '23'), (0x3254, 'M', '24'), (0x3255, 'M', '25'), (0x3256, 'M', '26'), (0x3257, 'M', '27'), (0x3258, 'M', '28'), (0x3259, 'M', '29'), (0x325A, 'M', '30'), (0x325B, 'M', '31'), (0x325C, 'M', '32'), (0x325D, 'M', '33'), (0x325E, 'M', '34'), (0x325F, 'M', '35'), (0x3260, 'M', 'ᄀ'), (0x3261, 'M', 'ᄂ'), (0x3262, 'M', 'ᄃ'), (0x3263, 'M', 'ᄅ'), (0x3264, 'M', 'ᄆ'), (0x3265, 'M', 'ᄇ'), (0x3266, 'M', 'ᄉ'), (0x3267, 'M', 'ᄋ'), (0x3268, 'M', 'ᄌ'), (0x3269, 'M', 'ᄎ'), (0x326A, 'M', 'ᄏ'), (0x326B, 'M', 'ᄐ'), (0x326C, 'M', 'ᄑ'), (0x326D, 'M', 'ᄒ'), (0x326E, 'M', '가'), (0x326F, 'M', '나'), (0x3270, 'M', '다'), (0x3271, 'M', '라'), (0x3272, 'M', '마'), (0x3273, 'M', '바'), (0x3274, 'M', '사'), (0x3275, 'M', '아'), (0x3276, 'M', '자'), (0x3277, 'M', '차'), (0x3278, 'M', '카'), (0x3279, 'M', '타'), (0x327A, 'M', '파'), (0x327B, 'M', '하'), (0x327C, 'M', '참고'), (0x327D, 'M', '주의'), (0x327E, 'M', '우'), (0x327F, 'V'), (0x3280, 'M', '一'), (0x3281, 'M', '二'), (0x3282, 'M', '三'), (0x3283, 'M', '四'), (0x3284, 'M', '五'), (0x3285, 'M', '六'), (0x3286, 'M', '七'), (0x3287, 'M', '八'), (0x3288, 'M', '九'), (0x3289, 'M', '十'), (0x328A, 'M', '月'), (0x328B, 'M', '火'), (0x328C, 'M', '水'), (0x328D, 'M', '木'), (0x328E, 'M', '金'), (0x328F, 'M', '土'), (0x3290, 'M', '日'), (0x3291, 'M', '株'), (0x3292, 'M', '有'), (0x3293, 'M', '社'), (0x3294, 'M', '名'), (0x3295, 'M', '特'), (0x3296, 'M', '財'), (0x3297, 'M', '祝'), (0x3298, 'M', '労'), (0x3299, 'M', '秘'), (0x329A, 'M', '男'), (0x329B, 'M', '女'), (0x329C, 'M', '適'), (0x329D, 'M', '優'), (0x329E, 'M', '印'), (0x329F, 'M', '注'), (0x32A0, 'M', '項'), (0x32A1, 'M', '休'), (0x32A2, 'M', '写'), (0x32A3, 'M', '正'), (0x32A4, 'M', '上'), (0x32A5, 'M', '中'), (0x32A6, 'M', '下'), (0x32A7, 'M', '左'), (0x32A8, 'M', '右'), (0x32A9, 'M', '医'), (0x32AA, 'M', '宗'), (0x32AB, 'M', '学'), (0x32AC, 'M', '監'), (0x32AD, 'M', '企'), (0x32AE, 'M', '資'), (0x32AF, 'M', '協'), (0x32B0, 'M', '夜'), (0x32B1, 'M', '36'), ] def _seg_32() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x32B2, 'M', '37'), (0x32B3, 'M', '38'), (0x32B4, 'M', '39'), (0x32B5, 'M', '40'), (0x32B6, 'M', '41'), (0x32B7, 'M', '42'), (0x32B8, 'M', '43'), (0x32B9, 'M', '44'), (0x32BA, 'M', '45'), (0x32BB, 'M', '46'), (0x32BC, 'M', '47'), (0x32BD, 'M', '48'), (0x32BE, 'M', '49'), (0x32BF, 'M', '50'), (0x32C0, 'M', '1月'), (0x32C1, 'M', '2月'), (0x32C2, 'M', '3月'), (0x32C3, 'M', '4月'), (0x32C4, 'M', '5月'), (0x32C5, 'M', '6月'), (0x32C6, 'M', '7月'), (0x32C7, 'M', '8月'), (0x32C8, 'M', '9月'), (0x32C9, 'M', '10月'), (0x32CA, 'M', '11月'), (0x32CB, 'M', '12月'), (0x32CC, 'M', 'hg'), (0x32CD, 'M', 'erg'), (0x32CE, 'M', 'ev'), (0x32CF, 'M', 'ltd'), (0x32D0, 'M', 'ア'), (0x32D1, 'M', 'イ'), (0x32D2, 'M', 'ウ'), (0x32D3, 'M', 'エ'), (0x32D4, 'M', 'オ'), (0x32D5, 'M', 'カ'), (0x32D6, 'M', 'キ'), (0x32D7, 'M', 'ク'), (0x32D8, 'M', 'ケ'), (0x32D9, 'M', 'コ'), (0x32DA, 'M', 'サ'), (0x32DB, 'M', 'シ'), (0x32DC, 'M', 'ス'), (0x32DD, 'M', 'セ'), (0x32DE, 'M', 'ソ'), (0x32DF, 'M', 'タ'), (0x32E0, 'M', 'チ'), (0x32E1, 'M', 'ツ'), (0x32E2, 'M', 'テ'), (0x32E3, 'M', 'ト'), (0x32E4, 'M', 'ナ'), (0x32E5, 'M', 'ニ'), (0x32E6, 'M', 'ヌ'), (0x32E7, 'M', 'ネ'), (0x32E8, 'M', 'ノ'), (0x32E9, 'M', 'ハ'), (0x32EA, 'M', 'ヒ'), (0x32EB, 'M', 'フ'), (0x32EC, 'M', 'ヘ'), (0x32ED, 'M', 'ホ'), (0x32EE, 'M', 'マ'), (0x32EF, 'M', 'ミ'), (0x32F0, 'M', 'ム'), (0x32F1, 'M', 'メ'), (0x32F2, 'M', 'モ'), (0x32F3, 'M', 'ヤ'), (0x32F4, 'M', 'ユ'), (0x32F5, 'M', 'ヨ'), (0x32F6, 'M', 'ラ'), (0x32F7, 'M', 'リ'), (0x32F8, 'M', 'ル'), (0x32F9, 'M', 'レ'), (0x32FA, 'M', 'ロ'), (0x32FB, 'M', 'ワ'), (0x32FC, 'M', 'ヰ'), (0x32FD, 'M', 'ヱ'), (0x32FE, 'M', 'ヲ'), (0x32FF, 'M', '令和'), (0x3300, 'M', 'アパート'), (0x3301, 'M', 'アルファ'), (0x3302, 'M', 'アンペア'), (0x3303, 'M', 'アール'), (0x3304, 'M', 'イニング'), (0x3305, 'M', 'インチ'), (0x3306, 'M', 'ウォン'), (0x3307, 'M', 'エスクード'), (0x3308, 'M', 'エーカー'), (0x3309, 'M', 'オンス'), (0x330A, 'M', 'オーム'), (0x330B, 'M', 'カイリ'), (0x330C, 'M', 'カラット'), (0x330D, 'M', 'カロリー'), (0x330E, 'M', 'ガロン'), (0x330F, 'M', 'ガンマ'), (0x3310, 'M', 'ギガ'), (0x3311, 'M', 'ギニー'), (0x3312, 'M', 'キュリー'), (0x3313, 'M', 'ギルダー'), (0x3314, 'M', 'キロ'), (0x3315, 'M', 'キログラム'), ] def _seg_33() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3316, 'M', 'キロメートル'), (0x3317, 'M', 'キロワット'), (0x3318, 'M', 'グラム'), (0x3319, 'M', 'グラムトン'), (0x331A, 'M', 'クルゼイロ'), (0x331B, 'M', 'クローネ'), (0x331C, 'M', 'ケース'), (0x331D, 'M', 'コルナ'), (0x331E, 'M', 'コーポ'), (0x331F, 'M', 'サイクル'), (0x3320, 'M', 'サンチーム'), (0x3321, 'M', 'シリング'), (0x3322, 'M', 'センチ'), (0x3323, 'M', 'セント'), (0x3324, 'M', 'ダース'), (0x3325, 'M', 'デシ'), (0x3326, 'M', 'ドル'), (0x3327, 'M', 'トン'), (0x3328, 'M', 'ナノ'), (0x3329, 'M', 'ノット'), (0x332A, 'M', 'ハイツ'), (0x332B, 'M', 'パーセント'), (0x332C, 'M', 'パーツ'), (0x332D, 'M', 'バーレル'), (0x332E, 'M', 'ピアストル'), (0x332F, 'M', 'ピクル'), (0x3330, 'M', 'ピコ'), (0x3331, 'M', 'ビル'), (0x3332, 'M', 'ファラッド'), (0x3333, 'M', 'フィート'), (0x3334, 'M', 'ブッシェル'), (0x3335, 'M', 'フラン'), (0x3336, 'M', 'ヘクタール'), (0x3337, 'M', 'ペソ'), (0x3338, 'M', 'ペニヒ'), (0x3339, 'M', 'ヘルツ'), (0x333A, 'M', 'ペンス'), (0x333B, 'M', 'ページ'), (0x333C, 'M', 'ベータ'), (0x333D, 'M', 'ポイント'), (0x333E, 'M', 'ボルト'), (0x333F, 'M', 'ホン'), (0x3340, 'M', 'ポンド'), (0x3341, 'M', 'ホール'), (0x3342, 'M', 'ホーン'), (0x3343, 'M', 'マイクロ'), (0x3344, 'M', 'マイル'), (0x3345, 'M', 'マッハ'), (0x3346, 'M', 'マルク'), (0x3347, 'M', 'マンション'), (0x3348, 'M', 'ミクロン'), (0x3349, 'M', 'ミリ'), (0x334A, 'M', 'ミリバール'), (0x334B, 'M', 'メガ'), (0x334C, 'M', 'メガトン'), (0x334D, 'M', 'メートル'), (0x334E, 'M', 'ヤード'), (0x334F, 'M', 'ヤール'), (0x3350, 'M', 'ユアン'), (0x3351, 'M', 'リットル'), (0x3352, 'M', 'リラ'), (0x3353, 'M', 'ルピー'), (0x3354, 'M', 'ルーブル'), (0x3355, 'M', 'レム'), (0x3356, 'M', 'レントゲン'), (0x3357, 'M', 'ワット'), (0x3358, 'M', '0点'), (0x3359, 'M', '1点'), (0x335A, 'M', '2点'), (0x335B, 'M', '3点'), (0x335C, 'M', '4点'), (0x335D, 'M', '5点'), (0x335E, 'M', '6点'), (0x335F, 'M', '7点'), (0x3360, 'M', '8点'), (0x3361, 'M', '9点'), (0x3362, 'M', '10点'), (0x3363, 'M', '11点'), (0x3364, 'M', '12点'), (0x3365, 'M', '13点'), (0x3366, 'M', '14点'), (0x3367, 'M', '15点'), (0x3368, 'M', '16点'), (0x3369, 'M', '17点'), (0x336A, 'M', '18点'), (0x336B, 'M', '19点'), (0x336C, 'M', '20点'), (0x336D, 'M', '21点'), (0x336E, 'M', '22点'), (0x336F, 'M', '23点'), (0x3370, 'M', '24点'), (0x3371, 'M', 'hpa'), (0x3372, 'M', 'da'), (0x3373, 'M', 'au'), (0x3374, 'M', 'bar'), (0x3375, 'M', 'ov'), (0x3376, 'M', 'pc'), (0x3377, 'M', 'dm'), (0x3378, 'M', 'dm2'), (0x3379, 'M', 'dm3'), ] def _seg_34() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x337A, 'M', 'iu'), (0x337B, 'M', '平成'), (0x337C, 'M', '昭和'), (0x337D, 'M', '大正'), (0x337E, 'M', '明治'), (0x337F, 'M', '株式会社'), (0x3380, 'M', 'pa'), (0x3381, 'M', 'na'), (0x3382, 'M', 'μa'), (0x3383, 'M', 'ma'), (0x3384, 'M', 'ka'), (0x3385, 'M', 'kb'), (0x3386, 'M', 'mb'), (0x3387, 'M', 'gb'), (0x3388, 'M', 'cal'), (0x3389, 'M', 'kcal'), (0x338A, 'M', 'pf'), (0x338B, 'M', 'nf'), (0x338C, 'M', 'μf'), (0x338D, 'M', 'μg'), (0x338E, 'M', 'mg'), (0x338F, 'M', 'kg'), (0x3390, 'M', 'hz'), (0x3391, 'M', 'khz'), (0x3392, 'M', 'mhz'), (0x3393, 'M', 'ghz'), (0x3394, 'M', 'thz'), (0x3395, 'M', 'μl'), (0x3396, 'M', 'ml'), (0x3397, 'M', 'dl'), (0x3398, 'M', 'kl'), (0x3399, 'M', 'fm'), (0x339A, 'M', 'nm'), (0x339B, 'M', 'μm'), (0x339C, 'M', 'mm'), (0x339D, 'M', 'cm'), (0x339E, 'M', 'km'), (0x339F, 'M', 'mm2'), (0x33A0, 'M', 'cm2'), (0x33A1, 'M', 'm2'), (0x33A2, 'M', 'km2'), (0x33A3, 'M', 'mm3'), (0x33A4, 'M', 'cm3'), (0x33A5, 'M', 'm3'), (0x33A6, 'M', 'km3'), (0x33A7, 'M', 'm∕s'), (0x33A8, 'M', 'm∕s2'), (0x33A9, 'M', 'pa'), (0x33AA, 'M', 'kpa'), (0x33AB, 'M', 'mpa'), (0x33AC, 'M', 'gpa'), (0x33AD, 'M', 'rad'), (0x33AE, 'M', 'rad∕s'), (0x33AF, 'M', 'rad∕s2'), (0x33B0, 'M', 'ps'), (0x33B1, 'M', 'ns'), (0x33B2, 'M', 'μs'), (0x33B3, 'M', 'ms'), (0x33B4, 'M', 'pv'), (0x33B5, 'M', 'nv'), (0x33B6, 'M', 'μv'), (0x33B7, 'M', 'mv'), (0x33B8, 'M', 'kv'), (0x33B9, 'M', 'mv'), (0x33BA, 'M', 'pw'), (0x33BB, 'M', 'nw'), (0x33BC, 'M', 'μw'), (0x33BD, 'M', 'mw'), (0x33BE, 'M', 'kw'), (0x33BF, 'M', 'mw'), (0x33C0, 'M', 'kω'), (0x33C1, 'M', 'mω'), (0x33C2, 'X'), (0x33C3, 'M', 'bq'), (0x33C4, 'M', 'cc'), (0x33C5, 'M', 'cd'), (0x33C6, 'M', 'c∕kg'), (0x33C7, 'X'), (0x33C8, 'M', 'db'), (0x33C9, 'M', 'gy'), (0x33CA, 'M', 'ha'), (0x33CB, 'M', 'hp'), (0x33CC, 'M', 'in'), (0x33CD, 'M', 'kk'), (0x33CE, 'M', 'km'), (0x33CF, 'M', 'kt'), (0x33D0, 'M', 'lm'), (0x33D1, 'M', 'ln'), (0x33D2, 'M', 'log'), (0x33D3, 'M', 'lx'), (0x33D4, 'M', 'mb'), (0x33D5, 'M', 'mil'), (0x33D6, 'M', 'mol'), (0x33D7, 'M', 'ph'), (0x33D8, 'X'), (0x33D9, 'M', 'ppm'), (0x33DA, 'M', 'pr'), (0x33DB, 'M', 'sr'), (0x33DC, 'M', 'sv'), (0x33DD, 'M', 'wb'), ] def _seg_35() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x33DE, 'M', 'v∕m'), (0x33DF, 'M', 'a∕m'), (0x33E0, 'M', '1日'), (0x33E1, 'M', '2日'), (0x33E2, 'M', '3日'), (0x33E3, 'M', '4日'), (0x33E4, 'M', '5日'), (0x33E5, 'M', '6日'), (0x33E6, 'M', '7日'), (0x33E7, 'M', '8日'), (0x33E8, 'M', '9日'), (0x33E9, 'M', '10日'), (0x33EA, 'M', '11日'), (0x33EB, 'M', '12日'), (0x33EC, 'M', '13日'), (0x33ED, 'M', '14日'), (0x33EE, 'M', '15日'), (0x33EF, 'M', '16日'), (0x33F0, 'M', '17日'), (0x33F1, 'M', '18日'), (0x33F2, 'M', '19日'), (0x33F3, 'M', '20日'), (0x33F4, 'M', '21日'), (0x33F5, 'M', '22日'), (0x33F6, 'M', '23日'), (0x33F7, 'M', '24日'), (0x33F8, 'M', '25日'), (0x33F9, 'M', '26日'), (0x33FA, 'M', '27日'), (0x33FB, 'M', '28日'), (0x33FC, 'M', '29日'), (0x33FD, 'M', '30日'), (0x33FE, 'M', '31日'), (0x33FF, 'M', 'gal'), (0x3400, 'V'), (0xA48D, 'X'), (0xA490, 'V'), (0xA4C7, 'X'), (0xA4D0, 'V'), (0xA62C, 'X'), (0xA640, 'M', 'ꙁ'), (0xA641, 'V'), (0xA642, 'M', 'ꙃ'), (0xA643, 'V'), (0xA644, 'M', 'ꙅ'), (0xA645, 'V'), (0xA646, 'M', 'ꙇ'), (0xA647, 'V'), (0xA648, 'M', 'ꙉ'), (0xA649, 'V'), (0xA64A, 'M', 'ꙋ'), (0xA64B, 'V'), (0xA64C, 'M', 'ꙍ'), (0xA64D, 'V'), (0xA64E, 'M', 'ꙏ'), (0xA64F, 'V'), (0xA650, 'M', 'ꙑ'), (0xA651, 'V'), (0xA652, 'M', 'ꙓ'), (0xA653, 'V'), (0xA654, 'M', 'ꙕ'), (0xA655, 'V'), (0xA656, 'M', 'ꙗ'), (0xA657, 'V'), (0xA658, 'M', 'ꙙ'), (0xA659, 'V'), (0xA65A, 'M', 'ꙛ'), (0xA65B, 'V'), (0xA65C, 'M', 'ꙝ'), (0xA65D, 'V'), (0xA65E, 'M', 'ꙟ'), (0xA65F, 'V'), (0xA660, 'M', 'ꙡ'), (0xA661, 'V'), (0xA662, 'M', 'ꙣ'), (0xA663, 'V'), (0xA664, 'M', 'ꙥ'), (0xA665, 'V'), (0xA666, 'M', 'ꙧ'), (0xA667, 'V'), (0xA668, 'M', 'ꙩ'), (0xA669, 'V'), (0xA66A, 'M', 'ꙫ'), (0xA66B, 'V'), (0xA66C, 'M', 'ꙭ'), (0xA66D, 'V'), (0xA680, 'M', 'ꚁ'), (0xA681, 'V'), (0xA682, 'M', 'ꚃ'), (0xA683, 'V'), (0xA684, 'M', 'ꚅ'), (0xA685, 'V'), (0xA686, 'M', 'ꚇ'), (0xA687, 'V'), (0xA688, 'M', 'ꚉ'), (0xA689, 'V'), (0xA68A, 'M', 'ꚋ'), (0xA68B, 'V'), (0xA68C, 'M', 'ꚍ'), (0xA68D, 'V'), ] def _seg_36() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA68E, 'M', 'ꚏ'), (0xA68F, 'V'), (0xA690, 'M', 'ꚑ'), (0xA691, 'V'), (0xA692, 'M', 'ꚓ'), (0xA693, 'V'), (0xA694, 'M', 'ꚕ'), (0xA695, 'V'), (0xA696, 'M', 'ꚗ'), (0xA697, 'V'), (0xA698, 'M', 'ꚙ'), (0xA699, 'V'), (0xA69A, 'M', 'ꚛ'), (0xA69B, 'V'), (0xA69C, 'M', 'ъ'), (0xA69D, 'M', 'ь'), (0xA69E, 'V'), (0xA6F8, 'X'), (0xA700, 'V'), (0xA722, 'M', 'ꜣ'), (0xA723, 'V'), (0xA724, 'M', 'ꜥ'), (0xA725, 'V'), (0xA726, 'M', 'ꜧ'), (0xA727, 'V'), (0xA728, 'M', 'ꜩ'), (0xA729, 'V'), (0xA72A, 'M', 'ꜫ'), (0xA72B, 'V'), (0xA72C, 'M', 'ꜭ'), (0xA72D, 'V'), (0xA72E, 'M', 'ꜯ'), (0xA72F, 'V'), (0xA732, 'M', 'ꜳ'), (0xA733, 'V'), (0xA734, 'M', 'ꜵ'), (0xA735, 'V'), (0xA736, 'M', 'ꜷ'), (0xA737, 'V'), (0xA738, 'M', 'ꜹ'), (0xA739, 'V'), (0xA73A, 'M', 'ꜻ'), (0xA73B, 'V'), (0xA73C, 'M', 'ꜽ'), (0xA73D, 'V'), (0xA73E, 'M', 'ꜿ'), (0xA73F, 'V'), (0xA740, 'M', 'ꝁ'), (0xA741, 'V'), (0xA742, 'M', 'ꝃ'), (0xA743, 'V'), (0xA744, 'M', 'ꝅ'), (0xA745, 'V'), (0xA746, 'M', 'ꝇ'), (0xA747, 'V'), (0xA748, 'M', 'ꝉ'), (0xA749, 'V'), (0xA74A, 'M', 'ꝋ'), (0xA74B, 'V'), (0xA74C, 'M', 'ꝍ'), (0xA74D, 'V'), (0xA74E, 'M', 'ꝏ'), (0xA74F, 'V'), (0xA750, 'M', 'ꝑ'), (0xA751, 'V'), (0xA752, 'M', 'ꝓ'), (0xA753, 'V'), (0xA754, 'M', 'ꝕ'), (0xA755, 'V'), (0xA756, 'M', 'ꝗ'), (0xA757, 'V'), (0xA758, 'M', 'ꝙ'), (0xA759, 'V'), (0xA75A, 'M', 'ꝛ'), (0xA75B, 'V'), (0xA75C, 'M', 'ꝝ'), (0xA75D, 'V'), (0xA75E, 'M', 'ꝟ'), (0xA75F, 'V'), (0xA760, 'M', 'ꝡ'), (0xA761, 'V'), (0xA762, 'M', 'ꝣ'), (0xA763, 'V'), (0xA764, 'M', 'ꝥ'), (0xA765, 'V'), (0xA766, 'M', 'ꝧ'), (0xA767, 'V'), (0xA768, 'M', 'ꝩ'), (0xA769, 'V'), (0xA76A, 'M', 'ꝫ'), (0xA76B, 'V'), (0xA76C, 'M', 'ꝭ'), (0xA76D, 'V'), (0xA76E, 'M', 'ꝯ'), (0xA76F, 'V'), (0xA770, 'M', 'ꝯ'), (0xA771, 'V'), (0xA779, 'M', 'ꝺ'), (0xA77A, 'V'), (0xA77B, 'M', 'ꝼ'), ] def _seg_37() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA77C, 'V'), (0xA77D, 'M', 'ᵹ'), (0xA77E, 'M', 'ꝿ'), (0xA77F, 'V'), (0xA780, 'M', 'ꞁ'), (0xA781, 'V'), (0xA782, 'M', 'ꞃ'), (0xA783, 'V'), (0xA784, 'M', 'ꞅ'), (0xA785, 'V'), (0xA786, 'M', 'ꞇ'), (0xA787, 'V'), (0xA78B, 'M', 'ꞌ'), (0xA78C, 'V'), (0xA78D, 'M', 'ɥ'), (0xA78E, 'V'), (0xA790, 'M', 'ꞑ'), (0xA791, 'V'), (0xA792, 'M', 'ꞓ'), (0xA793, 'V'), (0xA796, 'M', 'ꞗ'), (0xA797, 'V'), (0xA798, 'M', 'ꞙ'), (0xA799, 'V'), (0xA79A, 'M', 'ꞛ'), (0xA79B, 'V'), (0xA79C, 'M', 'ꞝ'), (0xA79D, 'V'), (0xA79E, 'M', 'ꞟ'), (0xA79F, 'V'), (0xA7A0, 'M', 'ꞡ'), (0xA7A1, 'V'), (0xA7A2, 'M', 'ꞣ'), (0xA7A3, 'V'), (0xA7A4, 'M', 'ꞥ'), (0xA7A5, 'V'), (0xA7A6, 'M', 'ꞧ'), (0xA7A7, 'V'), (0xA7A8, 'M', 'ꞩ'), (0xA7A9, 'V'), (0xA7AA, 'M', 'ɦ'), (0xA7AB, 'M', 'ɜ'), (0xA7AC, 'M', 'ɡ'), (0xA7AD, 'M', 'ɬ'), (0xA7AE, 'M', 'ɪ'), (0xA7AF, 'V'), (0xA7B0, 'M', 'ʞ'), (0xA7B1, 'M', 'ʇ'), (0xA7B2, 'M', 'ʝ'), (0xA7B3, 'M', 'ꭓ'), (0xA7B4, 'M', 'ꞵ'), (0xA7B5, 'V'), (0xA7B6, 'M', 'ꞷ'), (0xA7B7, 'V'), (0xA7B8, 'M', 'ꞹ'), (0xA7B9, 'V'), (0xA7BA, 'M', 'ꞻ'), (0xA7BB, 'V'), (0xA7BC, 'M', 'ꞽ'), (0xA7BD, 'V'), (0xA7BE, 'M', 'ꞿ'), (0xA7BF, 'V'), (0xA7C0, 'M', 'ꟁ'), (0xA7C1, 'V'), (0xA7C2, 'M', 'ꟃ'), (0xA7C3, 'V'), (0xA7C4, 'M', 'ꞔ'), (0xA7C5, 'M', 'ʂ'), (0xA7C6, 'M', 'ᶎ'), (0xA7C7, 'M', 'ꟈ'), (0xA7C8, 'V'), (0xA7C9, 'M', 'ꟊ'), (0xA7CA, 'V'), (0xA7CB, 'X'), (0xA7D0, 'M', 'ꟑ'), (0xA7D1, 'V'), (0xA7D2, 'X'), (0xA7D3, 'V'), (0xA7D4, 'X'), (0xA7D5, 'V'), (0xA7D6, 'M', 'ꟗ'), (0xA7D7, 'V'), (0xA7D8, 'M', 'ꟙ'), (0xA7D9, 'V'), (0xA7DA, 'X'), (0xA7F2, 'M', 'c'), (0xA7F3, 'M', 'f'), (0xA7F4, 'M', 'q'), (0xA7F5, 'M', 'ꟶ'), (0xA7F6, 'V'), (0xA7F8, 'M', 'ħ'), (0xA7F9, 'M', 'œ'), (0xA7FA, 'V'), (0xA82D, 'X'), (0xA830, 'V'), (0xA83A, 'X'), (0xA840, 'V'), (0xA878, 'X'), (0xA880, 'V'), (0xA8C6, 'X'), ] def _seg_38() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA8CE, 'V'), (0xA8DA, 'X'), (0xA8E0, 'V'), (0xA954, 'X'), (0xA95F, 'V'), (0xA97D, 'X'), (0xA980, 'V'), (0xA9CE, 'X'), (0xA9CF, 'V'), (0xA9DA, 'X'), (0xA9DE, 'V'), (0xA9FF, 'X'), (0xAA00, 'V'), (0xAA37, 'X'), (0xAA40, 'V'), (0xAA4E, 'X'), (0xAA50, 'V'), (0xAA5A, 'X'), (0xAA5C, 'V'), (0xAAC3, 'X'), (0xAADB, 'V'), (0xAAF7, 'X'), (0xAB01, 'V'), (0xAB07, 'X'), (0xAB09, 'V'), (0xAB0F, 'X'), (0xAB11, 'V'), (0xAB17, 'X'), (0xAB20, 'V'), (0xAB27, 'X'), (0xAB28, 'V'), (0xAB2F, 'X'), (0xAB30, 'V'), (0xAB5C, 'M', 'ꜧ'), (0xAB5D, 'M', 'ꬷ'), (0xAB5E, 'M', 'ɫ'), (0xAB5F, 'M', 'ꭒ'), (0xAB60, 'V'), (0xAB69, 'M', 'ʍ'), (0xAB6A, 'V'), (0xAB6C, 'X'), (0xAB70, 'M', 'Ꭰ'), (0xAB71, 'M', 'Ꭱ'), (0xAB72, 'M', 'Ꭲ'), (0xAB73, 'M', 'Ꭳ'), (0xAB74, 'M', 'Ꭴ'), (0xAB75, 'M', 'Ꭵ'), (0xAB76, 'M', 'Ꭶ'), (0xAB77, 'M', 'Ꭷ'), (0xAB78, 'M', 'Ꭸ'), (0xAB79, 'M', 'Ꭹ'), (0xAB7A, 'M', 'Ꭺ'), (0xAB7B, 'M', 'Ꭻ'), (0xAB7C, 'M', 'Ꭼ'), (0xAB7D, 'M', 'Ꭽ'), (0xAB7E, 'M', 'Ꭾ'), (0xAB7F, 'M', 'Ꭿ'), (0xAB80, 'M', 'Ꮀ'), (0xAB81, 'M', 'Ꮁ'), (0xAB82, 'M', 'Ꮂ'), (0xAB83, 'M', 'Ꮃ'), (0xAB84, 'M', 'Ꮄ'), (0xAB85, 'M', 'Ꮅ'), (0xAB86, 'M', 'Ꮆ'), (0xAB87, 'M', 'Ꮇ'), (0xAB88, 'M', 'Ꮈ'), (0xAB89, 'M', 'Ꮉ'), (0xAB8A, 'M', 'Ꮊ'), (0xAB8B, 'M', 'Ꮋ'), (0xAB8C, 'M', 'Ꮌ'), (0xAB8D, 'M', 'Ꮍ'), (0xAB8E, 'M', 'Ꮎ'), (0xAB8F, 'M', 'Ꮏ'), (0xAB90, 'M', 'Ꮐ'), (0xAB91, 'M', 'Ꮑ'), (0xAB92, 'M', 'Ꮒ'), (0xAB93, 'M', 'Ꮓ'), (0xAB94, 'M', 'Ꮔ'), (0xAB95, 'M', 'Ꮕ'), (0xAB96, 'M', 'Ꮖ'), (0xAB97, 'M', 'Ꮗ'), (0xAB98, 'M', 'Ꮘ'), (0xAB99, 'M', 'Ꮙ'), (0xAB9A, 'M', 'Ꮚ'), (0xAB9B, 'M', 'Ꮛ'), (0xAB9C, 'M', 'Ꮜ'), (0xAB9D, 'M', 'Ꮝ'), (0xAB9E, 'M', 'Ꮞ'), (0xAB9F, 'M', 'Ꮟ'), (0xABA0, 'M', 'Ꮠ'), (0xABA1, 'M', 'Ꮡ'), (0xABA2, 'M', 'Ꮢ'), (0xABA3, 'M', 'Ꮣ'), (0xABA4, 'M', 'Ꮤ'), (0xABA5, 'M', 'Ꮥ'), (0xABA6, 'M', 'Ꮦ'), (0xABA7, 'M', 'Ꮧ'), (0xABA8, 'M', 'Ꮨ'), (0xABA9, 'M', 'Ꮩ'), (0xABAA, 'M', 'Ꮪ'), ] def _seg_39() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xABAB, 'M', 'Ꮫ'), (0xABAC, 'M', 'Ꮬ'), (0xABAD, 'M', 'Ꮭ'), (0xABAE, 'M', 'Ꮮ'), (0xABAF, 'M', 'Ꮯ'), (0xABB0, 'M', 'Ꮰ'), (0xABB1, 'M', 'Ꮱ'), (0xABB2, 'M', 'Ꮲ'), (0xABB3, 'M', 'Ꮳ'), (0xABB4, 'M', 'Ꮴ'), (0xABB5, 'M', 'Ꮵ'), (0xABB6, 'M', 'Ꮶ'), (0xABB7, 'M', 'Ꮷ'), (0xABB8, 'M', 'Ꮸ'), (0xABB9, 'M', 'Ꮹ'), (0xABBA, 'M', 'Ꮺ'), (0xABBB, 'M', 'Ꮻ'), (0xABBC, 'M', 'Ꮼ'), (0xABBD, 'M', 'Ꮽ'), (0xABBE, 'M', 'Ꮾ'), (0xABBF, 'M', 'Ꮿ'), (0xABC0, 'V'), (0xABEE, 'X'), (0xABF0, 'V'), (0xABFA, 'X'), (0xAC00, 'V'), (0xD7A4, 'X'), (0xD7B0, 'V'), (0xD7C7, 'X'), (0xD7CB, 'V'), (0xD7FC, 'X'), (0xF900, 'M', '豈'), (0xF901, 'M', '更'), (0xF902, 'M', '車'), (0xF903, 'M', '賈'), (0xF904, 'M', '滑'), (0xF905, 'M', '串'), (0xF906, 'M', '句'), (0xF907, 'M', '龜'), (0xF909, 'M', '契'), (0xF90A, 'M', '金'), (0xF90B, 'M', '喇'), (0xF90C, 'M', '奈'), (0xF90D, 'M', '懶'), (0xF90E, 'M', '癩'), (0xF90F, 'M', '羅'), (0xF910, 'M', '蘿'), (0xF911, 'M', '螺'), (0xF912, 'M', '裸'), (0xF913, 'M', '邏'), (0xF914, 'M', '樂'), (0xF915, 'M', '洛'), (0xF916, 'M', '烙'), (0xF917, 'M', '珞'), (0xF918, 'M', '落'), (0xF919, 'M', '酪'), (0xF91A, 'M', '駱'), (0xF91B, 'M', '亂'), (0xF91C, 'M', '卵'), (0xF91D, 'M', '欄'), (0xF91E, 'M', '爛'), (0xF91F, 'M', '蘭'), (0xF920, 'M', '鸞'), (0xF921, 'M', '嵐'), (0xF922, 'M', '濫'), (0xF923, 'M', '藍'), (0xF924, 'M', '襤'), (0xF925, 'M', '拉'), (0xF926, 'M', '臘'), (0xF927, 'M', '蠟'), (0xF928, 'M', '廊'), (0xF929, 'M', '朗'), (0xF92A, 'M', '浪'), (0xF92B, 'M', '狼'), (0xF92C, 'M', '郎'), (0xF92D, 'M', '來'), (0xF92E, 'M', '冷'), (0xF92F, 'M', '勞'), (0xF930, 'M', '擄'), (0xF931, 'M', '櫓'), (0xF932, 'M', '爐'), (0xF933, 'M', '盧'), (0xF934, 'M', '老'), (0xF935, 'M', '蘆'), (0xF936, 'M', '虜'), (0xF937, 'M', '路'), (0xF938, 'M', '露'), (0xF939, 'M', '魯'), (0xF93A, 'M', '鷺'), (0xF93B, 'M', '碌'), (0xF93C, 'M', '祿'), (0xF93D, 'M', '綠'), (0xF93E, 'M', '菉'), (0xF93F, 'M', '錄'), (0xF940, 'M', '鹿'), (0xF941, 'M', '論'), (0xF942, 'M', '壟'), (0xF943, 'M', '弄'), (0xF944, 'M', '籠'), (0xF945, 'M', '聾'), ] def _seg_40() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xF946, 'M', '牢'), (0xF947, 'M', '磊'), (0xF948, 'M', '賂'), (0xF949, 'M', '雷'), (0xF94A, 'M', '壘'), (0xF94B, 'M', '屢'), (0xF94C, 'M', '樓'), (0xF94D, 'M', '淚'), (0xF94E, 'M', '漏'), (0xF94F, 'M', '累'), (0xF950, 'M', '縷'), (0xF951, 'M', '陋'), (0xF952, 'M', '勒'), (0xF953, 'M', '肋'), (0xF954, 'M', '凜'), (0xF955, 'M', '凌'), (0xF956, 'M', '稜'), (0xF957, 'M', '綾'), (0xF958, 'M', '菱'), (0xF959, 'M', '陵'), (0xF95A, 'M', '讀'), (0xF95B, 'M', '拏'), (0xF95C, 'M', '樂'), (0xF95D, 'M', '諾'), (0xF95E, 'M', '丹'), (0xF95F, 'M', '寧'), (0xF960, 'M', '怒'), (0xF961, 'M', '率'), (0xF962, 'M', '異'), (0xF963, 'M', '北'), (0xF964, 'M', '磻'), (0xF965, 'M', '便'), (0xF966, 'M', '復'), (0xF967, 'M', '不'), (0xF968, 'M', '泌'), (0xF969, 'M', '數'), (0xF96A, 'M', '索'), (0xF96B, 'M', '參'), (0xF96C, 'M', '塞'), (0xF96D, 'M', '省'), (0xF96E, 'M', '葉'), (0xF96F, 'M', '說'), (0xF970, 'M', '殺'), (0xF971, 'M', '辰'), (0xF972, 'M', '沈'), (0xF973, 'M', '拾'), (0xF974, 'M', '若'), (0xF975, 'M', '掠'), (0xF976, 'M', '略'), (0xF977, 'M', '亮'), (0xF978, 'M', '兩'), (0xF979, 'M', '凉'), (0xF97A, 'M', '梁'), (0xF97B, 'M', '糧'), (0xF97C, 'M', '良'), (0xF97D, 'M', '諒'), (0xF97E, 'M', '量'), (0xF97F, 'M', '勵'), (0xF980, 'M', '呂'), (0xF981, 'M', '女'), (0xF982, 'M', '廬'), (0xF983, 'M', '旅'), (0xF984, 'M', '濾'), (0xF985, 'M', '礪'), (0xF986, 'M', '閭'), (0xF987, 'M', '驪'), (0xF988, 'M', '麗'), (0xF989, 'M', '黎'), (0xF98A, 'M', '力'), (0xF98B, 'M', '曆'), (0xF98C, 'M', '歷'), (0xF98D, 'M', '轢'), (0xF98E, 'M', '年'), (0xF98F, 'M', '憐'), (0xF990, 'M', '戀'), (0xF991, 'M', '撚'), (0xF992, 'M', '漣'), (0xF993, 'M', '煉'), (0xF994, 'M', '璉'), (0xF995, 'M', '秊'), (0xF996, 'M', '練'), (0xF997, 'M', '聯'), (0xF998, 'M', '輦'), (0xF999, 'M', '蓮'), (0xF99A, 'M', '連'), (0xF99B, 'M', '鍊'), (0xF99C, 'M', '列'), (0xF99D, 'M', '劣'), (0xF99E, 'M', '咽'), (0xF99F, 'M', '烈'), (0xF9A0, 'M', '裂'), (0xF9A1, 'M', '說'), (0xF9A2, 'M', '廉'), (0xF9A3, 'M', '念'), (0xF9A4, 'M', '捻'), (0xF9A5, 'M', '殮'), (0xF9A6, 'M', '簾'), (0xF9A7, 'M', '獵'), (0xF9A8, 'M', '令'), (0xF9A9, 'M', '囹'), ] def _seg_41() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xF9AA, 'M', '寧'), (0xF9AB, 'M', '嶺'), (0xF9AC, 'M', '怜'), (0xF9AD, 'M', '玲'), (0xF9AE, 'M', '瑩'), (0xF9AF, 'M', '羚'), (0xF9B0, 'M', '聆'), (0xF9B1, 'M', '鈴'), (0xF9B2, 'M', '零'), (0xF9B3, 'M', '靈'), (0xF9B4, 'M', '領'), (0xF9B5, 'M', '例'), (0xF9B6, 'M', '禮'), (0xF9B7, 'M', '醴'), (0xF9B8, 'M', '隸'), (0xF9B9, 'M', '惡'), (0xF9BA, 'M', '了'), (0xF9BB, 'M', '僚'), (0xF9BC, 'M', '寮'), (0xF9BD, 'M', '尿'), (0xF9BE, 'M', '料'), (0xF9BF, 'M', '樂'), (0xF9C0, 'M', '燎'), (0xF9C1, 'M', '療'), (0xF9C2, 'M', '蓼'), (0xF9C3, 'M', '遼'), (0xF9C4, 'M', '龍'), (0xF9C5, 'M', '暈'), (0xF9C6, 'M', '阮'), (0xF9C7, 'M', '劉'), (0xF9C8, 'M', '杻'), (0xF9C9, 'M', '柳'), (0xF9CA, 'M', '流'), (0xF9CB, 'M', '溜'), (0xF9CC, 'M', '琉'), (0xF9CD, 'M', '留'), (0xF9CE, 'M', '硫'), (0xF9CF, 'M', '紐'), (0xF9D0, 'M', '類'), (0xF9D1, 'M', '六'), (0xF9D2, 'M', '戮'), (0xF9D3, 'M', '陸'), (0xF9D4, 'M', '倫'), (0xF9D5, 'M', '崙'), (0xF9D6, 'M', '淪'), (0xF9D7, 'M', '輪'), (0xF9D8, 'M', '律'), (0xF9D9, 'M', '慄'), (0xF9DA, 'M', '栗'), (0xF9DB, 'M', '率'), (0xF9DC, 'M', '隆'), (0xF9DD, 'M', '利'), (0xF9DE, 'M', '吏'), (0xF9DF, 'M', '履'), (0xF9E0, 'M', '易'), (0xF9E1, 'M', '李'), (0xF9E2, 'M', '梨'), (0xF9E3, 'M', '泥'), (0xF9E4, 'M', '理'), (0xF9E5, 'M', '痢'), (0xF9E6, 'M', '罹'), (0xF9E7, 'M', '裏'), (0xF9E8, 'M', '裡'), (0xF9E9, 'M', '里'), (0xF9EA, 'M', '離'), (0xF9EB, 'M', '匿'), (0xF9EC, 'M', '溺'), (0xF9ED, 'M', '吝'), (0xF9EE, 'M', '燐'), (0xF9EF, 'M', '璘'), (0xF9F0, 'M', '藺'), (0xF9F1, 'M', '隣'), (0xF9F2, 'M', '鱗'), (0xF9F3, 'M', '麟'), (0xF9F4, 'M', '林'), (0xF9F5, 'M', '淋'), (0xF9F6, 'M', '臨'), (0xF9F7, 'M', '立'), (0xF9F8, 'M', '笠'), (0xF9F9, 'M', '粒'), (0xF9FA, 'M', '狀'), (0xF9FB, 'M', '炙'), (0xF9FC, 'M', '識'), (0xF9FD, 'M', '什'), (0xF9FE, 'M', '茶'), (0xF9FF, 'M', '刺'), (0xFA00, 'M', '切'), (0xFA01, 'M', '度'), (0xFA02, 'M', '拓'), (0xFA03, 'M', '糖'), (0xFA04, 'M', '宅'), (0xFA05, 'M', '洞'), (0xFA06, 'M', '暴'), (0xFA07, 'M', '輻'), (0xFA08, 'M', '行'), (0xFA09, 'M', '降'), (0xFA0A, 'M', '見'), (0xFA0B, 'M', '廓'), (0xFA0C, 'M', '兀'), (0xFA0D, 'M', '嗀'), ] def _seg_42() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFA0E, 'V'), (0xFA10, 'M', '塚'), (0xFA11, 'V'), (0xFA12, 'M', '晴'), (0xFA13, 'V'), (0xFA15, 'M', '凞'), (0xFA16, 'M', '猪'), (0xFA17, 'M', '益'), (0xFA18, 'M', '礼'), (0xFA19, 'M', '神'), (0xFA1A, 'M', '祥'), (0xFA1B, 'M', '福'), (0xFA1C, 'M', '靖'), (0xFA1D, 'M', '精'), (0xFA1E, 'M', '羽'), (0xFA1F, 'V'), (0xFA20, 'M', '蘒'), (0xFA21, 'V'), (0xFA22, 'M', '諸'), (0xFA23, 'V'), (0xFA25, 'M', '逸'), (0xFA26, 'M', '都'), (0xFA27, 'V'), (0xFA2A, 'M', '飯'), (0xFA2B, 'M', '飼'), (0xFA2C, 'M', '館'), (0xFA2D, 'M', '鶴'), (0xFA2E, 'M', '郞'), (0xFA2F, 'M', '隷'), (0xFA30, 'M', '侮'), (0xFA31, 'M', '僧'), (0xFA32, 'M', '免'), (0xFA33, 'M', '勉'), (0xFA34, 'M', '勤'), (0xFA35, 'M', '卑'), (0xFA36, 'M', '喝'), (0xFA37, 'M', '嘆'), (0xFA38, 'M', '器'), (0xFA39, 'M', '塀'), (0xFA3A, 'M', '墨'), (0xFA3B, 'M', '層'), (0xFA3C, 'M', '屮'), (0xFA3D, 'M', '悔'), (0xFA3E, 'M', '慨'), (0xFA3F, 'M', '憎'), (0xFA40, 'M', '懲'), (0xFA41, 'M', '敏'), (0xFA42, 'M', '既'), (0xFA43, 'M', '暑'), (0xFA44, 'M', '梅'), (0xFA45, 'M', '海'), (0xFA46, 'M', '渚'), (0xFA47, 'M', '漢'), (0xFA48, 'M', '煮'), (0xFA49, 'M', '爫'), (0xFA4A, 'M', '琢'), (0xFA4B, 'M', '碑'), (0xFA4C, 'M', '社'), (0xFA4D, 'M', '祉'), (0xFA4E, 'M', '祈'), (0xFA4F, 'M', '祐'), (0xFA50, 'M', '祖'), (0xFA51, 'M', '祝'), (0xFA52, 'M', '禍'), (0xFA53, 'M', '禎'), (0xFA54, 'M', '穀'), (0xFA55, 'M', '突'), (0xFA56, 'M', '節'), (0xFA57, 'M', '練'), (0xFA58, 'M', '縉'), (0xFA59, 'M', '繁'), (0xFA5A, 'M', '署'), (0xFA5B, 'M', '者'), (0xFA5C, 'M', '臭'), (0xFA5D, 'M', '艹'), (0xFA5F, 'M', '著'), (0xFA60, 'M', '褐'), (0xFA61, 'M', '視'), (0xFA62, 'M', '謁'), (0xFA63, 'M', '謹'), (0xFA64, 'M', '賓'), (0xFA65, 'M', '贈'), (0xFA66, 'M', '辶'), (0xFA67, 'M', '逸'), (0xFA68, 'M', '難'), (0xFA69, 'M', '響'), (0xFA6A, 'M', '頻'), (0xFA6B, 'M', '恵'), (0xFA6C, 'M', '𤋮'), (0xFA6D, 'M', '舘'), (0xFA6E, 'X'), (0xFA70, 'M', '並'), (0xFA71, 'M', '况'), (0xFA72, 'M', '全'), (0xFA73, 'M', '侀'), (0xFA74, 'M', '充'), (0xFA75, 'M', '冀'), (0xFA76, 'M', '勇'), (0xFA77, 'M', '勺'), (0xFA78, 'M', '喝'), ] def _seg_43() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFA79, 'M', '啕'), (0xFA7A, 'M', '喙'), (0xFA7B, 'M', '嗢'), (0xFA7C, 'M', '塚'), (0xFA7D, 'M', '墳'), (0xFA7E, 'M', '奄'), (0xFA7F, 'M', '奔'), (0xFA80, 'M', '婢'), (0xFA81, 'M', '嬨'), (0xFA82, 'M', '廒'), (0xFA83, 'M', '廙'), (0xFA84, 'M', '彩'), (0xFA85, 'M', '徭'), (0xFA86, 'M', '惘'), (0xFA87, 'M', '慎'), (0xFA88, 'M', '愈'), (0xFA89, 'M', '憎'), (0xFA8A, 'M', '慠'), (0xFA8B, 'M', '懲'), (0xFA8C, 'M', '戴'), (0xFA8D, 'M', '揄'), (0xFA8E, 'M', '搜'), (0xFA8F, 'M', '摒'), (0xFA90, 'M', '敖'), (0xFA91, 'M', '晴'), (0xFA92, 'M', '朗'), (0xFA93, 'M', '望'), (0xFA94, 'M', '杖'), (0xFA95, 'M', '歹'), (0xFA96, 'M', '殺'), (0xFA97, 'M', '流'), (0xFA98, 'M', '滛'), (0xFA99, 'M', '滋'), (0xFA9A, 'M', '漢'), (0xFA9B, 'M', '瀞'), (0xFA9C, 'M', '煮'), (0xFA9D, 'M', '瞧'), (0xFA9E, 'M', '爵'), (0xFA9F, 'M', '犯'), (0xFAA0, 'M', '猪'), (0xFAA1, 'M', '瑱'), (0xFAA2, 'M', '甆'), (0xFAA3, 'M', '画'), (0xFAA4, 'M', '瘝'), (0xFAA5, 'M', '瘟'), (0xFAA6, 'M', '益'), (0xFAA7, 'M', '盛'), (0xFAA8, 'M', '直'), (0xFAA9, 'M', '睊'), (0xFAAA, 'M', '着'), (0xFAAB, 'M', '磌'), (0xFAAC, 'M', '窱'), (0xFAAD, 'M', '節'), (0xFAAE, 'M', '类'), (0xFAAF, 'M', '絛'), (0xFAB0, 'M', '練'), (0xFAB1, 'M', '缾'), (0xFAB2, 'M', '者'), (0xFAB3, 'M', '荒'), (0xFAB4, 'M', '華'), (0xFAB5, 'M', '蝹'), (0xFAB6, 'M', '襁'), (0xFAB7, 'M', '覆'), (0xFAB8, 'M', '視'), (0xFAB9, 'M', '調'), (0xFABA, 'M', '諸'), (0xFABB, 'M', '請'), (0xFABC, 'M', '謁'), (0xFABD, 'M', '諾'), (0xFABE, 'M', '諭'), (0xFABF, 'M', '謹'), (0xFAC0, 'M', '變'), (0xFAC1, 'M', '贈'), (0xFAC2, 'M', '輸'), (0xFAC3, 'M', '遲'), (0xFAC4, 'M', '醙'), (0xFAC5, 'M', '鉶'), (0xFAC6, 'M', '陼'), (0xFAC7, 'M', '難'), (0xFAC8, 'M', '靖'), (0xFAC9, 'M', '韛'), (0xFACA, 'M', '響'), (0xFACB, 'M', '頋'), (0xFACC, 'M', '頻'), (0xFACD, 'M', '鬒'), (0xFACE, 'M', '龜'), (0xFACF, 'M', '𢡊'), (0xFAD0, 'M', '𢡄'), (0xFAD1, 'M', '𣏕'), (0xFAD2, 'M', '㮝'), (0xFAD3, 'M', '䀘'), (0xFAD4, 'M', '䀹'), (0xFAD5, 'M', '𥉉'), (0xFAD6, 'M', '𥳐'), (0xFAD7, 'M', '𧻓'), (0xFAD8, 'M', '齃'), (0xFAD9, 'M', '龎'), (0xFADA, 'X'), (0xFB00, 'M', 'ff'), (0xFB01, 'M', 'fi'), ] def _seg_44() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFB02, 'M', 'fl'), (0xFB03, 'M', 'ffi'), (0xFB04, 'M', 'ffl'), (0xFB05, 'M', 'st'), (0xFB07, 'X'), (0xFB13, 'M', 'մն'), (0xFB14, 'M', 'մե'), (0xFB15, 'M', 'մի'), (0xFB16, 'M', 'վն'), (0xFB17, 'M', 'մխ'), (0xFB18, 'X'), (0xFB1D, 'M', 'יִ'), (0xFB1E, 'V'), (0xFB1F, 'M', 'ײַ'), (0xFB20, 'M', 'ע'), (0xFB21, 'M', 'א'), (0xFB22, 'M', 'ד'), (0xFB23, 'M', 'ה'), (0xFB24, 'M', 'כ'), (0xFB25, 'M', 'ל'), (0xFB26, 'M', 'ם'), (0xFB27, 'M', 'ר'), (0xFB28, 'M', 'ת'), (0xFB29, '3', '+'), (0xFB2A, 'M', 'שׁ'), (0xFB2B, 'M', 'שׂ'), (0xFB2C, 'M', 'שּׁ'), (0xFB2D, 'M', 'שּׂ'), (0xFB2E, 'M', 'אַ'), (0xFB2F, 'M', 'אָ'), (0xFB30, 'M', 'אּ'), (0xFB31, 'M', 'בּ'), (0xFB32, 'M', 'גּ'), (0xFB33, 'M', 'דּ'), (0xFB34, 'M', 'הּ'), (0xFB35, 'M', 'וּ'), (0xFB36, 'M', 'זּ'), (0xFB37, 'X'), (0xFB38, 'M', 'טּ'), (0xFB39, 'M', 'יּ'), (0xFB3A, 'M', 'ךּ'), (0xFB3B, 'M', 'כּ'), (0xFB3C, 'M', 'לּ'), (0xFB3D, 'X'), (0xFB3E, 'M', 'מּ'), (0xFB3F, 'X'), (0xFB40, 'M', 'נּ'), (0xFB41, 'M', 'סּ'), (0xFB42, 'X'), (0xFB43, 'M', 'ףּ'), (0xFB44, 'M', 'פּ'), (0xFB45, 'X'), (0xFB46, 'M', 'צּ'), (0xFB47, 'M', 'קּ'), (0xFB48, 'M', 'רּ'), (0xFB49, 'M', 'שּ'), (0xFB4A, 'M', 'תּ'), (0xFB4B, 'M', 'וֹ'), (0xFB4C, 'M', 'בֿ'), (0xFB4D, 'M', 'כֿ'), (0xFB4E, 'M', 'פֿ'), (0xFB4F, 'M', 'אל'), (0xFB50, 'M', 'ٱ'), (0xFB52, 'M', 'ٻ'), (0xFB56, 'M', 'پ'), (0xFB5A, 'M', 'ڀ'), (0xFB5E, 'M', 'ٺ'), (0xFB62, 'M', 'ٿ'), (0xFB66, 'M', 'ٹ'), (0xFB6A, 'M', 'ڤ'), (0xFB6E, 'M', 'ڦ'), (0xFB72, 'M', 'ڄ'), (0xFB76, 'M', 'ڃ'), (0xFB7A, 'M', 'چ'), (0xFB7E, 'M', 'ڇ'), (0xFB82, 'M', 'ڍ'), (0xFB84, 'M', 'ڌ'), (0xFB86, 'M', 'ڎ'), (0xFB88, 'M', 'ڈ'), (0xFB8A, 'M', 'ژ'), (0xFB8C, 'M', 'ڑ'), (0xFB8E, 'M', 'ک'), (0xFB92, 'M', 'گ'), (0xFB96, 'M', 'ڳ'), (0xFB9A, 'M', 'ڱ'), (0xFB9E, 'M', 'ں'), (0xFBA0, 'M', 'ڻ'), (0xFBA4, 'M', 'ۀ'), (0xFBA6, 'M', 'ہ'), (0xFBAA, 'M', 'ھ'), (0xFBAE, 'M', 'ے'), (0xFBB0, 'M', 'ۓ'), (0xFBB2, 'V'), (0xFBC3, 'X'), (0xFBD3, 'M', 'ڭ'), (0xFBD7, 'M', 'ۇ'), (0xFBD9, 'M', 'ۆ'), (0xFBDB, 'M', 'ۈ'), (0xFBDD, 'M', 'ۇٴ'), (0xFBDE, 'M', 'ۋ'), ] def _seg_45() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFBE0, 'M', 'ۅ'), (0xFBE2, 'M', 'ۉ'), (0xFBE4, 'M', 'ې'), (0xFBE8, 'M', 'ى'), (0xFBEA, 'M', 'ئا'), (0xFBEC, 'M', 'ئە'), (0xFBEE, 'M', 'ئو'), (0xFBF0, 'M', 'ئۇ'), (0xFBF2, 'M', 'ئۆ'), (0xFBF4, 'M', 'ئۈ'), (0xFBF6, 'M', 'ئې'), (0xFBF9, 'M', 'ئى'), (0xFBFC, 'M', 'ی'), (0xFC00, 'M', 'ئج'), (0xFC01, 'M', 'ئح'), (0xFC02, 'M', 'ئم'), (0xFC03, 'M', 'ئى'), (0xFC04, 'M', 'ئي'), (0xFC05, 'M', 'بج'), (0xFC06, 'M', 'بح'), (0xFC07, 'M', 'بخ'), (0xFC08, 'M', 'بم'), (0xFC09, 'M', 'بى'), (0xFC0A, 'M', 'بي'), (0xFC0B, 'M', 'تج'), (0xFC0C, 'M', 'تح'), (0xFC0D, 'M', 'تخ'), (0xFC0E, 'M', 'تم'), (0xFC0F, 'M', 'تى'), (0xFC10, 'M', 'تي'), (0xFC11, 'M', 'ثج'), (0xFC12, 'M', 'ثم'), (0xFC13, 'M', 'ثى'), (0xFC14, 'M', 'ثي'), (0xFC15, 'M', 'جح'), (0xFC16, 'M', 'جم'), (0xFC17, 'M', 'حج'), (0xFC18, 'M', 'حم'), (0xFC19, 'M', 'خج'), (0xFC1A, 'M', 'خح'), (0xFC1B, 'M', 'خم'), (0xFC1C, 'M', 'سج'), (0xFC1D, 'M', 'سح'), (0xFC1E, 'M', 'سخ'), (0xFC1F, 'M', 'سم'), (0xFC20, 'M', 'صح'), (0xFC21, 'M', 'صم'), (0xFC22, 'M', 'ضج'), (0xFC23, 'M', 'ضح'), (0xFC24, 'M', 'ضخ'), (0xFC25, 'M', 'ضم'), (0xFC26, 'M', 'طح'), (0xFC27, 'M', 'طم'), (0xFC28, 'M', 'ظم'), (0xFC29, 'M', 'عج'), (0xFC2A, 'M', 'عم'), (0xFC2B, 'M', 'غج'), (0xFC2C, 'M', 'غم'), (0xFC2D, 'M', 'فج'), (0xFC2E, 'M', 'فح'), (0xFC2F, 'M', 'فخ'), (0xFC30, 'M', 'فم'), (0xFC31, 'M', 'فى'), (0xFC32, 'M', 'في'), (0xFC33, 'M', 'قح'), (0xFC34, 'M', 'قم'), (0xFC35, 'M', 'قى'), (0xFC36, 'M', 'قي'), (0xFC37, 'M', 'كا'), (0xFC38, 'M', 'كج'), (0xFC39, 'M', 'كح'), (0xFC3A, 'M', 'كخ'), (0xFC3B, 'M', 'كل'), (0xFC3C, 'M', 'كم'), (0xFC3D, 'M', 'كى'), (0xFC3E, 'M', 'كي'), (0xFC3F, 'M', 'لج'), (0xFC40, 'M', 'لح'), (0xFC41, 'M', 'لخ'), (0xFC42, 'M', 'لم'), (0xFC43, 'M', 'لى'), (0xFC44, 'M', 'لي'), (0xFC45, 'M', 'مج'), (0xFC46, 'M', 'مح'), (0xFC47, 'M', 'مخ'), (0xFC48, 'M', 'مم'), (0xFC49, 'M', 'مى'), (0xFC4A, 'M', 'مي'), (0xFC4B, 'M', 'نج'), (0xFC4C, 'M', 'نح'), (0xFC4D, 'M', 'نخ'), (0xFC4E, 'M', 'نم'), (0xFC4F, 'M', 'نى'), (0xFC50, 'M', 'ني'), (0xFC51, 'M', 'هج'), (0xFC52, 'M', 'هم'), (0xFC53, 'M', 'هى'), (0xFC54, 'M', 'هي'), (0xFC55, 'M', 'يج'), (0xFC56, 'M', 'يح'), ] def _seg_46() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFC57, 'M', 'يخ'), (0xFC58, 'M', 'يم'), (0xFC59, 'M', 'يى'), (0xFC5A, 'M', 'يي'), (0xFC5B, 'M', 'ذٰ'), (0xFC5C, 'M', 'رٰ'), (0xFC5D, 'M', 'ىٰ'), (0xFC5E, '3', ' ٌّ'), (0xFC5F, '3', ' ٍّ'), (0xFC60, '3', ' َّ'), (0xFC61, '3', ' ُّ'), (0xFC62, '3', ' ِّ'), (0xFC63, '3', ' ّٰ'), (0xFC64, 'M', 'ئر'), (0xFC65, 'M', 'ئز'), (0xFC66, 'M', 'ئم'), (0xFC67, 'M', 'ئن'), (0xFC68, 'M', 'ئى'), (0xFC69, 'M', 'ئي'), (0xFC6A, 'M', 'بر'), (0xFC6B, 'M', 'بز'), (0xFC6C, 'M', 'بم'), (0xFC6D, 'M', 'بن'), (0xFC6E, 'M', 'بى'), (0xFC6F, 'M', 'بي'), (0xFC70, 'M', 'تر'), (0xFC71, 'M', 'تز'), (0xFC72, 'M', 'تم'), (0xFC73, 'M', 'تن'), (0xFC74, 'M', 'تى'), (0xFC75, 'M', 'تي'), (0xFC76, 'M', 'ثر'), (0xFC77, 'M', 'ثز'), (0xFC78, 'M', 'ثم'), (0xFC79, 'M', 'ثن'), (0xFC7A, 'M', 'ثى'), (0xFC7B, 'M', 'ثي'), (0xFC7C, 'M', 'فى'), (0xFC7D, 'M', 'في'), (0xFC7E, 'M', 'قى'), (0xFC7F, 'M', 'قي'), (0xFC80, 'M', 'كا'), (0xFC81, 'M', 'كل'), (0xFC82, 'M', 'كم'), (0xFC83, 'M', 'كى'), (0xFC84, 'M', 'كي'), (0xFC85, 'M', 'لم'), (0xFC86, 'M', 'لى'), (0xFC87, 'M', 'لي'), (0xFC88, 'M', 'ما'), (0xFC89, 'M', 'مم'), (0xFC8A, 'M', 'نر'), (0xFC8B, 'M', 'نز'), (0xFC8C, 'M', 'نم'), (0xFC8D, 'M', 'نن'), (0xFC8E, 'M', 'نى'), (0xFC8F, 'M', 'ني'), (0xFC90, 'M', 'ىٰ'), (0xFC91, 'M', 'ير'), (0xFC92, 'M', 'يز'), (0xFC93, 'M', 'يم'), (0xFC94, 'M', 'ين'), (0xFC95, 'M', 'يى'), (0xFC96, 'M', 'يي'), (0xFC97, 'M', 'ئج'), (0xFC98, 'M', 'ئح'), (0xFC99, 'M', 'ئخ'), (0xFC9A, 'M', 'ئم'), (0xFC9B, 'M', 'ئه'), (0xFC9C, 'M', 'بج'), (0xFC9D, 'M', 'بح'), (0xFC9E, 'M', 'بخ'), (0xFC9F, 'M', 'بم'), (0xFCA0, 'M', 'به'), (0xFCA1, 'M', 'تج'), (0xFCA2, 'M', 'تح'), (0xFCA3, 'M', 'تخ'), (0xFCA4, 'M', 'تم'), (0xFCA5, 'M', 'ته'), (0xFCA6, 'M', 'ثم'), (0xFCA7, 'M', 'جح'), (0xFCA8, 'M', 'جم'), (0xFCA9, 'M', 'حج'), (0xFCAA, 'M', 'حم'), (0xFCAB, 'M', 'خج'), (0xFCAC, 'M', 'خم'), (0xFCAD, 'M', 'سج'), (0xFCAE, 'M', 'سح'), (0xFCAF, 'M', 'سخ'), (0xFCB0, 'M', 'سم'), (0xFCB1, 'M', 'صح'), (0xFCB2, 'M', 'صخ'), (0xFCB3, 'M', 'صم'), (0xFCB4, 'M', 'ضج'), (0xFCB5, 'M', 'ضح'), (0xFCB6, 'M', 'ضخ'), (0xFCB7, 'M', 'ضم'), (0xFCB8, 'M', 'طح'), (0xFCB9, 'M', 'ظم'), (0xFCBA, 'M', 'عج'), ] def _seg_47() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFCBB, 'M', 'عم'), (0xFCBC, 'M', 'غج'), (0xFCBD, 'M', 'غم'), (0xFCBE, 'M', 'فج'), (0xFCBF, 'M', 'فح'), (0xFCC0, 'M', 'فخ'), (0xFCC1, 'M', 'فم'), (0xFCC2, 'M', 'قح'), (0xFCC3, 'M', 'قم'), (0xFCC4, 'M', 'كج'), (0xFCC5, 'M', 'كح'), (0xFCC6, 'M', 'كخ'), (0xFCC7, 'M', 'كل'), (0xFCC8, 'M', 'كم'), (0xFCC9, 'M', 'لج'), (0xFCCA, 'M', 'لح'), (0xFCCB, 'M', 'لخ'), (0xFCCC, 'M', 'لم'), (0xFCCD, 'M', 'له'), (0xFCCE, 'M', 'مج'), (0xFCCF, 'M', 'مح'), (0xFCD0, 'M', 'مخ'), (0xFCD1, 'M', 'مم'), (0xFCD2, 'M', 'نج'), (0xFCD3, 'M', 'نح'), (0xFCD4, 'M', 'نخ'), (0xFCD5, 'M', 'نم'), (0xFCD6, 'M', 'نه'), (0xFCD7, 'M', 'هج'), (0xFCD8, 'M', 'هم'), (0xFCD9, 'M', 'هٰ'), (0xFCDA, 'M', 'يج'), (0xFCDB, 'M', 'يح'), (0xFCDC, 'M', 'يخ'), (0xFCDD, 'M', 'يم'), (0xFCDE, 'M', 'يه'), (0xFCDF, 'M', 'ئم'), (0xFCE0, 'M', 'ئه'), (0xFCE1, 'M', 'بم'), (0xFCE2, 'M', 'به'), (0xFCE3, 'M', 'تم'), (0xFCE4, 'M', 'ته'), (0xFCE5, 'M', 'ثم'), (0xFCE6, 'M', 'ثه'), (0xFCE7, 'M', 'سم'), (0xFCE8, 'M', 'سه'), (0xFCE9, 'M', 'شم'), (0xFCEA, 'M', 'شه'), (0xFCEB, 'M', 'كل'), (0xFCEC, 'M', 'كم'), (0xFCED, 'M', 'لم'), (0xFCEE, 'M', 'نم'), (0xFCEF, 'M', 'نه'), (0xFCF0, 'M', 'يم'), (0xFCF1, 'M', 'يه'), (0xFCF2, 'M', 'ـَّ'), (0xFCF3, 'M', 'ـُّ'), (0xFCF4, 'M', 'ـِّ'), (0xFCF5, 'M', 'طى'), (0xFCF6, 'M', 'طي'), (0xFCF7, 'M', 'عى'), (0xFCF8, 'M', 'عي'), (0xFCF9, 'M', 'غى'), (0xFCFA, 'M', 'غي'), (0xFCFB, 'M', 'سى'), (0xFCFC, 'M', 'سي'), (0xFCFD, 'M', 'شى'), (0xFCFE, 'M', 'شي'), (0xFCFF, 'M', 'حى'), (0xFD00, 'M', 'حي'), (0xFD01, 'M', 'جى'), (0xFD02, 'M', 'جي'), (0xFD03, 'M', 'خى'), (0xFD04, 'M', 'خي'), (0xFD05, 'M', 'صى'), (0xFD06, 'M', 'صي'), (0xFD07, 'M', 'ضى'), (0xFD08, 'M', 'ضي'), (0xFD09, 'M', 'شج'), (0xFD0A, 'M', 'شح'), (0xFD0B, 'M', 'شخ'), (0xFD0C, 'M', 'شم'), (0xFD0D, 'M', 'شر'), (0xFD0E, 'M', 'سر'), (0xFD0F, 'M', 'صر'), (0xFD10, 'M', 'ضر'), (0xFD11, 'M', 'طى'), (0xFD12, 'M', 'طي'), (0xFD13, 'M', 'عى'), (0xFD14, 'M', 'عي'), (0xFD15, 'M', 'غى'), (0xFD16, 'M', 'غي'), (0xFD17, 'M', 'سى'), (0xFD18, 'M', 'سي'), (0xFD19, 'M', 'شى'), (0xFD1A, 'M', 'شي'), (0xFD1B, 'M', 'حى'), (0xFD1C, 'M', 'حي'), (0xFD1D, 'M', 'جى'), (0xFD1E, 'M', 'جي'), ] def _seg_48() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFD1F, 'M', 'خى'), (0xFD20, 'M', 'خي'), (0xFD21, 'M', 'صى'), (0xFD22, 'M', 'صي'), (0xFD23, 'M', 'ضى'), (0xFD24, 'M', 'ضي'), (0xFD25, 'M', 'شج'), (0xFD26, 'M', 'شح'), (0xFD27, 'M', 'شخ'), (0xFD28, 'M', 'شم'), (0xFD29, 'M', 'شر'), (0xFD2A, 'M', 'سر'), (0xFD2B, 'M', 'صر'), (0xFD2C, 'M', 'ضر'), (0xFD2D, 'M', 'شج'), (0xFD2E, 'M', 'شح'), (0xFD2F, 'M', 'شخ'), (0xFD30, 'M', 'شم'), (0xFD31, 'M', 'سه'), (0xFD32, 'M', 'شه'), (0xFD33, 'M', 'طم'), (0xFD34, 'M', 'سج'), (0xFD35, 'M', 'سح'), (0xFD36, 'M', 'سخ'), (0xFD37, 'M', 'شج'), (0xFD38, 'M', 'شح'), (0xFD39, 'M', 'شخ'), (0xFD3A, 'M', 'طم'), (0xFD3B, 'M', 'ظم'), (0xFD3C, 'M', 'اً'), (0xFD3E, 'V'), (0xFD50, 'M', 'تجم'), (0xFD51, 'M', 'تحج'), (0xFD53, 'M', 'تحم'), (0xFD54, 'M', 'تخم'), (0xFD55, 'M', 'تمج'), (0xFD56, 'M', 'تمح'), (0xFD57, 'M', 'تمخ'), (0xFD58, 'M', 'جمح'), (0xFD5A, 'M', 'حمي'), (0xFD5B, 'M', 'حمى'), (0xFD5C, 'M', 'سحج'), (0xFD5D, 'M', 'سجح'), (0xFD5E, 'M', 'سجى'), (0xFD5F, 'M', 'سمح'), (0xFD61, 'M', 'سمج'), (0xFD62, 'M', 'سمم'), (0xFD64, 'M', 'صحح'), (0xFD66, 'M', 'صمم'), (0xFD67, 'M', 'شحم'), (0xFD69, 'M', 'شجي'), (0xFD6A, 'M', 'شمخ'), (0xFD6C, 'M', 'شمم'), (0xFD6E, 'M', 'ضحى'), (0xFD6F, 'M', 'ضخم'), (0xFD71, 'M', 'طمح'), (0xFD73, 'M', 'طمم'), (0xFD74, 'M', 'طمي'), (0xFD75, 'M', 'عجم'), (0xFD76, 'M', 'عمم'), (0xFD78, 'M', 'عمى'), (0xFD79, 'M', 'غمم'), (0xFD7A, 'M', 'غمي'), (0xFD7B, 'M', 'غمى'), (0xFD7C, 'M', 'فخم'), (0xFD7E, 'M', 'قمح'), (0xFD7F, 'M', 'قمم'), (0xFD80, 'M', 'لحم'), (0xFD81, 'M', 'لحي'), (0xFD82, 'M', 'لحى'), (0xFD83, 'M', 'لجج'), (0xFD85, 'M', 'لخم'), (0xFD87, 'M', 'لمح'), (0xFD89, 'M', 'محج'), (0xFD8A, 'M', 'محم'), (0xFD8B, 'M', 'محي'), (0xFD8C, 'M', 'مجح'), (0xFD8D, 'M', 'مجم'), (0xFD8E, 'M', 'مخج'), (0xFD8F, 'M', 'مخم'), (0xFD90, 'X'), (0xFD92, 'M', 'مجخ'), (0xFD93, 'M', 'همج'), (0xFD94, 'M', 'همم'), (0xFD95, 'M', 'نحم'), (0xFD96, 'M', 'نحى'), (0xFD97, 'M', 'نجم'), (0xFD99, 'M', 'نجى'), (0xFD9A, 'M', 'نمي'), (0xFD9B, 'M', 'نمى'), (0xFD9C, 'M', 'يمم'), (0xFD9E, 'M', 'بخي'), (0xFD9F, 'M', 'تجي'), (0xFDA0, 'M', 'تجى'), (0xFDA1, 'M', 'تخي'), (0xFDA2, 'M', 'تخى'), (0xFDA3, 'M', 'تمي'), (0xFDA4, 'M', 'تمى'), (0xFDA5, 'M', 'جمي'), (0xFDA6, 'M', 'جحى'), ] def _seg_49() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFDA7, 'M', 'جمى'), (0xFDA8, 'M', 'سخى'), (0xFDA9, 'M', 'صحي'), (0xFDAA, 'M', 'شحي'), (0xFDAB, 'M', 'ضحي'), (0xFDAC, 'M', 'لجي'), (0xFDAD, 'M', 'لمي'), (0xFDAE, 'M', 'يحي'), (0xFDAF, 'M', 'يجي'), (0xFDB0, 'M', 'يمي'), (0xFDB1, 'M', 'ممي'), (0xFDB2, 'M', 'قمي'), (0xFDB3, 'M', 'نحي'), (0xFDB4, 'M', 'قمح'), (0xFDB5, 'M', 'لحم'), (0xFDB6, 'M', 'عمي'), (0xFDB7, 'M', 'كمي'), (0xFDB8, 'M', 'نجح'), (0xFDB9, 'M', 'مخي'), (0xFDBA, 'M', 'لجم'), (0xFDBB, 'M', 'كمم'), (0xFDBC, 'M', 'لجم'), (0xFDBD, 'M', 'نجح'), (0xFDBE, 'M', 'جحي'), (0xFDBF, 'M', 'حجي'), (0xFDC0, 'M', 'مجي'), (0xFDC1, 'M', 'فمي'), (0xFDC2, 'M', 'بحي'), (0xFDC3, 'M', 'كمم'), (0xFDC4, 'M', 'عجم'), (0xFDC5, 'M', 'صمم'), (0xFDC6, 'M', 'سخي'), (0xFDC7, 'M', 'نجي'), (0xFDC8, 'X'), (0xFDCF, 'V'), (0xFDD0, 'X'), (0xFDF0, 'M', 'صلے'), (0xFDF1, 'M', 'قلے'), (0xFDF2, 'M', 'الله'), (0xFDF3, 'M', 'اكبر'), (0xFDF4, 'M', 'محمد'), (0xFDF5, 'M', 'صلعم'), (0xFDF6, 'M', 'رسول'), (0xFDF7, 'M', 'عليه'), (0xFDF8, 'M', 'وسلم'), (0xFDF9, 'M', 'صلى'), (0xFDFA, '3', 'صلى الله عليه وسلم'), (0xFDFB, '3', 'جل جلاله'), (0xFDFC, 'M', 'ریال'), (0xFDFD, 'V'), (0xFE00, 'I'), (0xFE10, '3', ','), (0xFE11, 'M', '、'), (0xFE12, 'X'), (0xFE13, '3', ':'), (0xFE14, '3', ';'), (0xFE15, '3', '!'), (0xFE16, '3', '?'), (0xFE17, 'M', '〖'), (0xFE18, 'M', '〗'), (0xFE19, 'X'), (0xFE20, 'V'), (0xFE30, 'X'), (0xFE31, 'M', '—'), (0xFE32, 'M', '–'), (0xFE33, '3', '_'), (0xFE35, '3', '('), (0xFE36, '3', ')'), (0xFE37, '3', '{'), (0xFE38, '3', '}'), (0xFE39, 'M', '〔'), (0xFE3A, 'M', '〕'), (0xFE3B, 'M', '【'), (0xFE3C, 'M', '】'), (0xFE3D, 'M', '《'), (0xFE3E, 'M', '》'), (0xFE3F, 'M', '〈'), (0xFE40, 'M', '〉'), (0xFE41, 'M', '「'), (0xFE42, 'M', '」'), (0xFE43, 'M', '『'), (0xFE44, 'M', '』'), (0xFE45, 'V'), (0xFE47, '3', '['), (0xFE48, '3', ']'), (0xFE49, '3', ' ̅'), (0xFE4D, '3', '_'), (0xFE50, '3', ','), (0xFE51, 'M', '、'), (0xFE52, 'X'), (0xFE54, '3', ';'), (0xFE55, '3', ':'), (0xFE56, '3', '?'), (0xFE57, '3', '!'), (0xFE58, 'M', '—'), (0xFE59, '3', '('), (0xFE5A, '3', ')'), (0xFE5B, '3', '{'), (0xFE5C, '3', '}'), (0xFE5D, 'M', '〔'), ] def _seg_50() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFE5E, 'M', '〕'), (0xFE5F, '3', '#'), (0xFE60, '3', '&'), (0xFE61, '3', '*'), (0xFE62, '3', '+'), (0xFE63, 'M', '-'), (0xFE64, '3', '<'), (0xFE65, '3', '>'), (0xFE66, '3', '='), (0xFE67, 'X'), (0xFE68, '3', '\\'), (0xFE69, '3', '$'), (0xFE6A, '3', '%'), (0xFE6B, '3', '@'), (0xFE6C, 'X'), (0xFE70, '3', ' ً'), (0xFE71, 'M', 'ـً'), (0xFE72, '3', ' ٌ'), (0xFE73, 'V'), (0xFE74, '3', ' ٍ'), (0xFE75, 'X'), (0xFE76, '3', ' َ'), (0xFE77, 'M', 'ـَ'), (0xFE78, '3', ' ُ'), (0xFE79, 'M', 'ـُ'), (0xFE7A, '3', ' ِ'), (0xFE7B, 'M', 'ـِ'), (0xFE7C, '3', ' ّ'), (0xFE7D, 'M', 'ـّ'), (0xFE7E, '3', ' ْ'), (0xFE7F, 'M', 'ـْ'), (0xFE80, 'M', 'ء'), (0xFE81, 'M', 'آ'), (0xFE83, 'M', 'أ'), (0xFE85, 'M', 'ؤ'), (0xFE87, 'M', 'إ'), (0xFE89, 'M', 'ئ'), (0xFE8D, 'M', 'ا'), (0xFE8F, 'M', 'ب'), (0xFE93, 'M', 'ة'), (0xFE95, 'M', 'ت'), (0xFE99, 'M', 'ث'), (0xFE9D, 'M', 'ج'), (0xFEA1, 'M', 'ح'), (0xFEA5, 'M', 'خ'), (0xFEA9, 'M', 'د'), (0xFEAB, 'M', 'ذ'), (0xFEAD, 'M', 'ر'), (0xFEAF, 'M', 'ز'), (0xFEB1, 'M', 'س'), (0xFEB5, 'M', 'ش'), (0xFEB9, 'M', 'ص'), (0xFEBD, 'M', 'ض'), (0xFEC1, 'M', 'ط'), (0xFEC5, 'M', 'ظ'), (0xFEC9, 'M', 'ع'), (0xFECD, 'M', 'غ'), (0xFED1, 'M', 'ف'), (0xFED5, 'M', 'ق'), (0xFED9, 'M', 'ك'), (0xFEDD, 'M', 'ل'), (0xFEE1, 'M', 'م'), (0xFEE5, 'M', 'ن'), (0xFEE9, 'M', 'ه'), (0xFEED, 'M', 'و'), (0xFEEF, 'M', 'ى'), (0xFEF1, 'M', 'ي'), (0xFEF5, 'M', 'لآ'), (0xFEF7, 'M', 'لأ'), (0xFEF9, 'M', 'لإ'), (0xFEFB, 'M', 'لا'), (0xFEFD, 'X'), (0xFEFF, 'I'), (0xFF00, 'X'), (0xFF01, '3', '!'), (0xFF02, '3', '"'), (0xFF03, '3', '#'), (0xFF04, '3', '$'), (0xFF05, '3', '%'), (0xFF06, '3', '&'), (0xFF07, '3', '\''), (0xFF08, '3', '('), (0xFF09, '3', ')'), (0xFF0A, '3', '*'), (0xFF0B, '3', '+'), (0xFF0C, '3', ','), (0xFF0D, 'M', '-'), (0xFF0E, 'M', '.'), (0xFF0F, '3', '/'), (0xFF10, 'M', '0'), (0xFF11, 'M', '1'), (0xFF12, 'M', '2'), (0xFF13, 'M', '3'), (0xFF14, 'M', '4'), (0xFF15, 'M', '5'), (0xFF16, 'M', '6'), (0xFF17, 'M', '7'), (0xFF18, 'M', '8'), (0xFF19, 'M', '9'), (0xFF1A, '3', ':'), ] def _seg_51() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFF1B, '3', ';'), (0xFF1C, '3', '<'), (0xFF1D, '3', '='), (0xFF1E, '3', '>'), (0xFF1F, '3', '?'), (0xFF20, '3', '@'), (0xFF21, 'M', 'a'), (0xFF22, 'M', 'b'), (0xFF23, 'M', 'c'), (0xFF24, 'M', 'd'), (0xFF25, 'M', 'e'), (0xFF26, 'M', 'f'), (0xFF27, 'M', 'g'), (0xFF28, 'M', 'h'), (0xFF29, 'M', 'i'), (0xFF2A, 'M', 'j'), (0xFF2B, 'M', 'k'), (0xFF2C, 'M', 'l'), (0xFF2D, 'M', 'm'), (0xFF2E, 'M', 'n'), (0xFF2F, 'M', 'o'), (0xFF30, 'M', 'p'), (0xFF31, 'M', 'q'), (0xFF32, 'M', 'r'), (0xFF33, 'M', 's'), (0xFF34, 'M', 't'), (0xFF35, 'M', 'u'), (0xFF36, 'M', 'v'), (0xFF37, 'M', 'w'), (0xFF38, 'M', 'x'), (0xFF39, 'M', 'y'), (0xFF3A, 'M', 'z'), (0xFF3B, '3', '['), (0xFF3C, '3', '\\'), (0xFF3D, '3', ']'), (0xFF3E, '3', '^'), (0xFF3F, '3', '_'), (0xFF40, '3', '`'), (0xFF41, 'M', 'a'), (0xFF42, 'M', 'b'), (0xFF43, 'M', 'c'), (0xFF44, 'M', 'd'), (0xFF45, 'M', 'e'), (0xFF46, 'M', 'f'), (0xFF47, 'M', 'g'), (0xFF48, 'M', 'h'), (0xFF49, 'M', 'i'), (0xFF4A, 'M', 'j'), (0xFF4B, 'M', 'k'), (0xFF4C, 'M', 'l'), (0xFF4D, 'M', 'm'), (0xFF4E, 'M', 'n'), (0xFF4F, 'M', 'o'), (0xFF50, 'M', 'p'), (0xFF51, 'M', 'q'), (0xFF52, 'M', 'r'), (0xFF53, 'M', 's'), (0xFF54, 'M', 't'), (0xFF55, 'M', 'u'), (0xFF56, 'M', 'v'), (0xFF57, 'M', 'w'), (0xFF58, 'M', 'x'), (0xFF59, 'M', 'y'), (0xFF5A, 'M', 'z'), (0xFF5B, '3', '{'), (0xFF5C, '3', '|'), (0xFF5D, '3', '}'), (0xFF5E, '3', '~'), (0xFF5F, 'M', '⦅'), (0xFF60, 'M', '⦆'), (0xFF61, 'M', '.'), (0xFF62, 'M', '「'), (0xFF63, 'M', '」'), (0xFF64, 'M', '、'), (0xFF65, 'M', '・'), (0xFF66, 'M', 'ヲ'), (0xFF67, 'M', 'ァ'), (0xFF68, 'M', 'ィ'), (0xFF69, 'M', 'ゥ'), (0xFF6A, 'M', 'ェ'), (0xFF6B, 'M', 'ォ'), (0xFF6C, 'M', 'ャ'), (0xFF6D, 'M', 'ュ'), (0xFF6E, 'M', 'ョ'), (0xFF6F, 'M', 'ッ'), (0xFF70, 'M', 'ー'), (0xFF71, 'M', 'ア'), (0xFF72, 'M', 'イ'), (0xFF73, 'M', 'ウ'), (0xFF74, 'M', 'エ'), (0xFF75, 'M', 'オ'), (0xFF76, 'M', 'カ'), (0xFF77, 'M', 'キ'), (0xFF78, 'M', 'ク'), (0xFF79, 'M', 'ケ'), (0xFF7A, 'M', 'コ'), (0xFF7B, 'M', 'サ'), (0xFF7C, 'M', 'シ'), (0xFF7D, 'M', 'ス'), (0xFF7E, 'M', 'セ'), ] def _seg_52() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFF7F, 'M', 'ソ'), (0xFF80, 'M', 'タ'), (0xFF81, 'M', 'チ'), (0xFF82, 'M', 'ツ'), (0xFF83, 'M', 'テ'), (0xFF84, 'M', 'ト'), (0xFF85, 'M', 'ナ'), (0xFF86, 'M', 'ニ'), (0xFF87, 'M', 'ヌ'), (0xFF88, 'M', 'ネ'), (0xFF89, 'M', 'ノ'), (0xFF8A, 'M', 'ハ'), (0xFF8B, 'M', 'ヒ'), (0xFF8C, 'M', 'フ'), (0xFF8D, 'M', 'ヘ'), (0xFF8E, 'M', 'ホ'), (0xFF8F, 'M', 'マ'), (0xFF90, 'M', 'ミ'), (0xFF91, 'M', 'ム'), (0xFF92, 'M', 'メ'), (0xFF93, 'M', 'モ'), (0xFF94, 'M', 'ヤ'), (0xFF95, 'M', 'ユ'), (0xFF96, 'M', 'ヨ'), (0xFF97, 'M', 'ラ'), (0xFF98, 'M', 'リ'), (0xFF99, 'M', 'ル'), (0xFF9A, 'M', 'レ'), (0xFF9B, 'M', 'ロ'), (0xFF9C, 'M', 'ワ'), (0xFF9D, 'M', 'ン'), (0xFF9E, 'M', '゙'), (0xFF9F, 'M', '゚'), (0xFFA0, 'X'), (0xFFA1, 'M', 'ᄀ'), (0xFFA2, 'M', 'ᄁ'), (0xFFA3, 'M', 'ᆪ'), (0xFFA4, 'M', 'ᄂ'), (0xFFA5, 'M', 'ᆬ'), (0xFFA6, 'M', 'ᆭ'), (0xFFA7, 'M', 'ᄃ'), (0xFFA8, 'M', 'ᄄ'), (0xFFA9, 'M', 'ᄅ'), (0xFFAA, 'M', 'ᆰ'), (0xFFAB, 'M', 'ᆱ'), (0xFFAC, 'M', 'ᆲ'), (0xFFAD, 'M', 'ᆳ'), (0xFFAE, 'M', 'ᆴ'), (0xFFAF, 'M', 'ᆵ'), (0xFFB0, 'M', 'ᄚ'), (0xFFB1, 'M', 'ᄆ'), (0xFFB2, 'M', 'ᄇ'), (0xFFB3, 'M', 'ᄈ'), (0xFFB4, 'M', 'ᄡ'), (0xFFB5, 'M', 'ᄉ'), (0xFFB6, 'M', 'ᄊ'), (0xFFB7, 'M', 'ᄋ'), (0xFFB8, 'M', 'ᄌ'), (0xFFB9, 'M', 'ᄍ'), (0xFFBA, 'M', 'ᄎ'), (0xFFBB, 'M', 'ᄏ'), (0xFFBC, 'M', 'ᄐ'), (0xFFBD, 'M', 'ᄑ'), (0xFFBE, 'M', 'ᄒ'), (0xFFBF, 'X'), (0xFFC2, 'M', 'ᅡ'), (0xFFC3, 'M', 'ᅢ'), (0xFFC4, 'M', 'ᅣ'), (0xFFC5, 'M', 'ᅤ'), (0xFFC6, 'M', 'ᅥ'), (0xFFC7, 'M', 'ᅦ'), (0xFFC8, 'X'), (0xFFCA, 'M', 'ᅧ'), (0xFFCB, 'M', 'ᅨ'), (0xFFCC, 'M', 'ᅩ'), (0xFFCD, 'M', 'ᅪ'), (0xFFCE, 'M', 'ᅫ'), (0xFFCF, 'M', 'ᅬ'), (0xFFD0, 'X'), (0xFFD2, 'M', 'ᅭ'), (0xFFD3, 'M', 'ᅮ'), (0xFFD4, 'M', 'ᅯ'), (0xFFD5, 'M', 'ᅰ'), (0xFFD6, 'M', 'ᅱ'), (0xFFD7, 'M', 'ᅲ'), (0xFFD8, 'X'), (0xFFDA, 'M', 'ᅳ'), (0xFFDB, 'M', 'ᅴ'), (0xFFDC, 'M', 'ᅵ'), (0xFFDD, 'X'), (0xFFE0, 'M', '¢'), (0xFFE1, 'M', '£'), (0xFFE2, 'M', '¬'), (0xFFE3, '3', ' ̄'), (0xFFE4, 'M', '¦'), (0xFFE5, 'M', '¥'), (0xFFE6, 'M', '₩'), (0xFFE7, 'X'), (0xFFE8, 'M', '│'), (0xFFE9, 'M', '←'), ] def _seg_53() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFFEA, 'M', '↑'), (0xFFEB, 'M', '→'), (0xFFEC, 'M', '↓'), (0xFFED, 'M', '■'), (0xFFEE, 'M', '○'), (0xFFEF, 'X'), (0x10000, 'V'), (0x1000C, 'X'), (0x1000D, 'V'), (0x10027, 'X'), (0x10028, 'V'), (0x1003B, 'X'), (0x1003C, 'V'), (0x1003E, 'X'), (0x1003F, 'V'), (0x1004E, 'X'), (0x10050, 'V'), (0x1005E, 'X'), (0x10080, 'V'), (0x100FB, 'X'), (0x10100, 'V'), (0x10103, 'X'), (0x10107, 'V'), (0x10134, 'X'), (0x10137, 'V'), (0x1018F, 'X'), (0x10190, 'V'), (0x1019D, 'X'), (0x101A0, 'V'), (0x101A1, 'X'), (0x101D0, 'V'), (0x101FE, 'X'), (0x10280, 'V'), (0x1029D, 'X'), (0x102A0, 'V'), (0x102D1, 'X'), (0x102E0, 'V'), (0x102FC, 'X'), (0x10300, 'V'), (0x10324, 'X'), (0x1032D, 'V'), (0x1034B, 'X'), (0x10350, 'V'), (0x1037B, 'X'), (0x10380, 'V'), (0x1039E, 'X'), (0x1039F, 'V'), (0x103C4, 'X'), (0x103C8, 'V'), (0x103D6, 'X'), (0x10400, 'M', '𐐨'), (0x10401, 'M', '𐐩'), (0x10402, 'M', '𐐪'), (0x10403, 'M', '𐐫'), (0x10404, 'M', '𐐬'), (0x10405, 'M', '𐐭'), (0x10406, 'M', '𐐮'), (0x10407, 'M', '𐐯'), (0x10408, 'M', '𐐰'), (0x10409, 'M', '𐐱'), (0x1040A, 'M', '𐐲'), (0x1040B, 'M', '𐐳'), (0x1040C, 'M', '𐐴'), (0x1040D, 'M', '𐐵'), (0x1040E, 'M', '𐐶'), (0x1040F, 'M', '𐐷'), (0x10410, 'M', '𐐸'), (0x10411, 'M', '𐐹'), (0x10412, 'M', '𐐺'), (0x10413, 'M', '𐐻'), (0x10414, 'M', '𐐼'), (0x10415, 'M', '𐐽'), (0x10416, 'M', '𐐾'), (0x10417, 'M', '𐐿'), (0x10418, 'M', '𐑀'), (0x10419, 'M', '𐑁'), (0x1041A, 'M', '𐑂'), (0x1041B, 'M', '𐑃'), (0x1041C, 'M', '𐑄'), (0x1041D, 'M', '𐑅'), (0x1041E, 'M', '𐑆'), (0x1041F, 'M', '𐑇'), (0x10420, 'M', '𐑈'), (0x10421, 'M', '𐑉'), (0x10422, 'M', '𐑊'), (0x10423, 'M', '𐑋'), (0x10424, 'M', '𐑌'), (0x10425, 'M', '𐑍'), (0x10426, 'M', '𐑎'), (0x10427, 'M', '𐑏'), (0x10428, 'V'), (0x1049E, 'X'), (0x104A0, 'V'), (0x104AA, 'X'), (0x104B0, 'M', '𐓘'), (0x104B1, 'M', '𐓙'), (0x104B2, 'M', '𐓚'), (0x104B3, 'M', '𐓛'), (0x104B4, 'M', '𐓜'), (0x104B5, 'M', '𐓝'), ] def _seg_54() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x104B6, 'M', '𐓞'), (0x104B7, 'M', '𐓟'), (0x104B8, 'M', '𐓠'), (0x104B9, 'M', '𐓡'), (0x104BA, 'M', '𐓢'), (0x104BB, 'M', '𐓣'), (0x104BC, 'M', '𐓤'), (0x104BD, 'M', '𐓥'), (0x104BE, 'M', '𐓦'), (0x104BF, 'M', '𐓧'), (0x104C0, 'M', '𐓨'), (0x104C1, 'M', '𐓩'), (0x104C2, 'M', '𐓪'), (0x104C3, 'M', '𐓫'), (0x104C4, 'M', '𐓬'), (0x104C5, 'M', '𐓭'), (0x104C6, 'M', '𐓮'), (0x104C7, 'M', '𐓯'), (0x104C8, 'M', '𐓰'), (0x104C9, 'M', '𐓱'), (0x104CA, 'M', '𐓲'), (0x104CB, 'M', '𐓳'), (0x104CC, 'M', '𐓴'), (0x104CD, 'M', '𐓵'), (0x104CE, 'M', '𐓶'), (0x104CF, 'M', '𐓷'), (0x104D0, 'M', '𐓸'), (0x104D1, 'M', '𐓹'), (0x104D2, 'M', '𐓺'), (0x104D3, 'M', '𐓻'), (0x104D4, 'X'), (0x104D8, 'V'), (0x104FC, 'X'), (0x10500, 'V'), (0x10528, 'X'), (0x10530, 'V'), (0x10564, 'X'), (0x1056F, 'V'), (0x10570, 'M', '𐖗'), (0x10571, 'M', '𐖘'), (0x10572, 'M', '𐖙'), (0x10573, 'M', '𐖚'), (0x10574, 'M', '𐖛'), (0x10575, 'M', '𐖜'), (0x10576, 'M', '𐖝'), (0x10577, 'M', '𐖞'), (0x10578, 'M', '𐖟'), (0x10579, 'M', '𐖠'), (0x1057A, 'M', '𐖡'), (0x1057B, 'X'), (0x1057C, 'M', '𐖣'), (0x1057D, 'M', '𐖤'), (0x1057E, 'M', '𐖥'), (0x1057F, 'M', '𐖦'), (0x10580, 'M', '𐖧'), (0x10581, 'M', '𐖨'), (0x10582, 'M', '𐖩'), (0x10583, 'M', '𐖪'), (0x10584, 'M', '𐖫'), (0x10585, 'M', '𐖬'), (0x10586, 'M', '𐖭'), (0x10587, 'M', '𐖮'), (0x10588, 'M', '𐖯'), (0x10589, 'M', '𐖰'), (0x1058A, 'M', '𐖱'), (0x1058B, 'X'), (0x1058C, 'M', '𐖳'), (0x1058D, 'M', '𐖴'), (0x1058E, 'M', '𐖵'), (0x1058F, 'M', '𐖶'), (0x10590, 'M', '𐖷'), (0x10591, 'M', '𐖸'), (0x10592, 'M', '𐖹'), (0x10593, 'X'), (0x10594, 'M', '𐖻'), (0x10595, 'M', '𐖼'), (0x10596, 'X'), (0x10597, 'V'), (0x105A2, 'X'), (0x105A3, 'V'), (0x105B2, 'X'), (0x105B3, 'V'), (0x105BA, 'X'), (0x105BB, 'V'), (0x105BD, 'X'), (0x10600, 'V'), (0x10737, 'X'), (0x10740, 'V'), (0x10756, 'X'), (0x10760, 'V'), (0x10768, 'X'), (0x10780, 'V'), (0x10781, 'M', 'ː'), (0x10782, 'M', 'ˑ'), (0x10783, 'M', 'æ'), (0x10784, 'M', 'ʙ'), (0x10785, 'M', 'ɓ'), (0x10786, 'X'), (0x10787, 'M', 'ʣ'), (0x10788, 'M', 'ꭦ'), ] def _seg_55() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x10789, 'M', 'ʥ'), (0x1078A, 'M', 'ʤ'), (0x1078B, 'M', 'ɖ'), (0x1078C, 'M', 'ɗ'), (0x1078D, 'M', 'ᶑ'), (0x1078E, 'M', 'ɘ'), (0x1078F, 'M', 'ɞ'), (0x10790, 'M', 'ʩ'), (0x10791, 'M', 'ɤ'), (0x10792, 'M', 'ɢ'), (0x10793, 'M', 'ɠ'), (0x10794, 'M', 'ʛ'), (0x10795, 'M', 'ħ'), (0x10796, 'M', 'ʜ'), (0x10797, 'M', 'ɧ'), (0x10798, 'M', 'ʄ'), (0x10799, 'M', 'ʪ'), (0x1079A, 'M', 'ʫ'), (0x1079B, 'M', 'ɬ'), (0x1079C, 'M', '𝼄'), (0x1079D, 'M', 'ꞎ'), (0x1079E, 'M', 'ɮ'), (0x1079F, 'M', '𝼅'), (0x107A0, 'M', 'ʎ'), (0x107A1, 'M', '𝼆'), (0x107A2, 'M', 'ø'), (0x107A3, 'M', 'ɶ'), (0x107A4, 'M', 'ɷ'), (0x107A5, 'M', 'q'), (0x107A6, 'M', 'ɺ'), (0x107A7, 'M', '𝼈'), (0x107A8, 'M', 'ɽ'), (0x107A9, 'M', 'ɾ'), (0x107AA, 'M', 'ʀ'), (0x107AB, 'M', 'ʨ'), (0x107AC, 'M', 'ʦ'), (0x107AD, 'M', 'ꭧ'), (0x107AE, 'M', 'ʧ'), (0x107AF, 'M', 'ʈ'), (0x107B0, 'M', 'ⱱ'), (0x107B1, 'X'), (0x107B2, 'M', 'ʏ'), (0x107B3, 'M', 'ʡ'), (0x107B4, 'M', 'ʢ'), (0x107B5, 'M', 'ʘ'), (0x107B6, 'M', 'ǀ'), (0x107B7, 'M', 'ǁ'), (0x107B8, 'M', 'ǂ'), (0x107B9, 'M', '𝼊'), (0x107BA, 'M', '𝼞'), (0x107BB, 'X'), (0x10800, 'V'), (0x10806, 'X'), (0x10808, 'V'), (0x10809, 'X'), (0x1080A, 'V'), (0x10836, 'X'), (0x10837, 'V'), (0x10839, 'X'), (0x1083C, 'V'), (0x1083D, 'X'), (0x1083F, 'V'), (0x10856, 'X'), (0x10857, 'V'), (0x1089F, 'X'), (0x108A7, 'V'), (0x108B0, 'X'), (0x108E0, 'V'), (0x108F3, 'X'), (0x108F4, 'V'), (0x108F6, 'X'), (0x108FB, 'V'), (0x1091C, 'X'), (0x1091F, 'V'), (0x1093A, 'X'), (0x1093F, 'V'), (0x10940, 'X'), (0x10980, 'V'), (0x109B8, 'X'), (0x109BC, 'V'), (0x109D0, 'X'), (0x109D2, 'V'), (0x10A04, 'X'), (0x10A05, 'V'), (0x10A07, 'X'), (0x10A0C, 'V'), (0x10A14, 'X'), (0x10A15, 'V'), (0x10A18, 'X'), (0x10A19, 'V'), (0x10A36, 'X'), (0x10A38, 'V'), (0x10A3B, 'X'), (0x10A3F, 'V'), (0x10A49, 'X'), (0x10A50, 'V'), (0x10A59, 'X'), (0x10A60, 'V'), (0x10AA0, 'X'), (0x10AC0, 'V'), ] def _seg_56() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x10AE7, 'X'), (0x10AEB, 'V'), (0x10AF7, 'X'), (0x10B00, 'V'), (0x10B36, 'X'), (0x10B39, 'V'), (0x10B56, 'X'), (0x10B58, 'V'), (0x10B73, 'X'), (0x10B78, 'V'), (0x10B92, 'X'), (0x10B99, 'V'), (0x10B9D, 'X'), (0x10BA9, 'V'), (0x10BB0, 'X'), (0x10C00, 'V'), (0x10C49, 'X'), (0x10C80, 'M', '𐳀'), (0x10C81, 'M', '𐳁'), (0x10C82, 'M', '𐳂'), (0x10C83, 'M', '𐳃'), (0x10C84, 'M', '𐳄'), (0x10C85, 'M', '𐳅'), (0x10C86, 'M', '𐳆'), (0x10C87, 'M', '𐳇'), (0x10C88, 'M', '𐳈'), (0x10C89, 'M', '𐳉'), (0x10C8A, 'M', '𐳊'), (0x10C8B, 'M', '𐳋'), (0x10C8C, 'M', '𐳌'), (0x10C8D, 'M', '𐳍'), (0x10C8E, 'M', '𐳎'), (0x10C8F, 'M', '𐳏'), (0x10C90, 'M', '𐳐'), (0x10C91, 'M', '𐳑'), (0x10C92, 'M', '𐳒'), (0x10C93, 'M', '𐳓'), (0x10C94, 'M', '𐳔'), (0x10C95, 'M', '𐳕'), (0x10C96, 'M', '𐳖'), (0x10C97, 'M', '𐳗'), (0x10C98, 'M', '𐳘'), (0x10C99, 'M', '𐳙'), (0x10C9A, 'M', '𐳚'), (0x10C9B, 'M', '𐳛'), (0x10C9C, 'M', '𐳜'), (0x10C9D, 'M', '𐳝'), (0x10C9E, 'M', '𐳞'), (0x10C9F, 'M', '𐳟'), (0x10CA0, 'M', '𐳠'), (0x10CA1, 'M', '𐳡'), (0x10CA2, 'M', '𐳢'), (0x10CA3, 'M', '𐳣'), (0x10CA4, 'M', '𐳤'), (0x10CA5, 'M', '𐳥'), (0x10CA6, 'M', '𐳦'), (0x10CA7, 'M', '𐳧'), (0x10CA8, 'M', '𐳨'), (0x10CA9, 'M', '𐳩'), (0x10CAA, 'M', '𐳪'), (0x10CAB, 'M', '𐳫'), (0x10CAC, 'M', '𐳬'), (0x10CAD, 'M', '𐳭'), (0x10CAE, 'M', '𐳮'), (0x10CAF, 'M', '𐳯'), (0x10CB0, 'M', '𐳰'), (0x10CB1, 'M', '𐳱'), (0x10CB2, 'M', '𐳲'), (0x10CB3, 'X'), (0x10CC0, 'V'), (0x10CF3, 'X'), (0x10CFA, 'V'), (0x10D28, 'X'), (0x10D30, 'V'), (0x10D3A, 'X'), (0x10E60, 'V'), (0x10E7F, 'X'), (0x10E80, 'V'), (0x10EAA, 'X'), (0x10EAB, 'V'), (0x10EAE, 'X'), (0x10EB0, 'V'), (0x10EB2, 'X'), (0x10F00, 'V'), (0x10F28, 'X'), (0x10F30, 'V'), (0x10F5A, 'X'), (0x10F70, 'V'), (0x10F8A, 'X'), (0x10FB0, 'V'), (0x10FCC, 'X'), (0x10FE0, 'V'), (0x10FF7, 'X'), (0x11000, 'V'), (0x1104E, 'X'), (0x11052, 'V'), (0x11076, 'X'), (0x1107F, 'V'), (0x110BD, 'X'), (0x110BE, 'V'), ] def _seg_57() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x110C3, 'X'), (0x110D0, 'V'), (0x110E9, 'X'), (0x110F0, 'V'), (0x110FA, 'X'), (0x11100, 'V'), (0x11135, 'X'), (0x11136, 'V'), (0x11148, 'X'), (0x11150, 'V'), (0x11177, 'X'), (0x11180, 'V'), (0x111E0, 'X'), (0x111E1, 'V'), (0x111F5, 'X'), (0x11200, 'V'), (0x11212, 'X'), (0x11213, 'V'), (0x1123F, 'X'), (0x11280, 'V'), (0x11287, 'X'), (0x11288, 'V'), (0x11289, 'X'), (0x1128A, 'V'), (0x1128E, 'X'), (0x1128F, 'V'), (0x1129E, 'X'), (0x1129F, 'V'), (0x112AA, 'X'), (0x112B0, 'V'), (0x112EB, 'X'), (0x112F0, 'V'), (0x112FA, 'X'), (0x11300, 'V'), (0x11304, 'X'), (0x11305, 'V'), (0x1130D, 'X'), (0x1130F, 'V'), (0x11311, 'X'), (0x11313, 'V'), (0x11329, 'X'), (0x1132A, 'V'), (0x11331, 'X'), (0x11332, 'V'), (0x11334, 'X'), (0x11335, 'V'), (0x1133A, 'X'), (0x1133B, 'V'), (0x11345, 'X'), (0x11347, 'V'), (0x11349, 'X'), (0x1134B, 'V'), (0x1134E, 'X'), (0x11350, 'V'), (0x11351, 'X'), (0x11357, 'V'), (0x11358, 'X'), (0x1135D, 'V'), (0x11364, 'X'), (0x11366, 'V'), (0x1136D, 'X'), (0x11370, 'V'), (0x11375, 'X'), (0x11400, 'V'), (0x1145C, 'X'), (0x1145D, 'V'), (0x11462, 'X'), (0x11480, 'V'), (0x114C8, 'X'), (0x114D0, 'V'), (0x114DA, 'X'), (0x11580, 'V'), (0x115B6, 'X'), (0x115B8, 'V'), (0x115DE, 'X'), (0x11600, 'V'), (0x11645, 'X'), (0x11650, 'V'), (0x1165A, 'X'), (0x11660, 'V'), (0x1166D, 'X'), (0x11680, 'V'), (0x116BA, 'X'), (0x116C0, 'V'), (0x116CA, 'X'), (0x11700, 'V'), (0x1171B, 'X'), (0x1171D, 'V'), (0x1172C, 'X'), (0x11730, 'V'), (0x11747, 'X'), (0x11800, 'V'), (0x1183C, 'X'), (0x118A0, 'M', '𑣀'), (0x118A1, 'M', '𑣁'), (0x118A2, 'M', '𑣂'), (0x118A3, 'M', '𑣃'), (0x118A4, 'M', '𑣄'), (0x118A5, 'M', '𑣅'), (0x118A6, 'M', '𑣆'), ] def _seg_58() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x118A7, 'M', '𑣇'), (0x118A8, 'M', '𑣈'), (0x118A9, 'M', '𑣉'), (0x118AA, 'M', '𑣊'), (0x118AB, 'M', '𑣋'), (0x118AC, 'M', '𑣌'), (0x118AD, 'M', '𑣍'), (0x118AE, 'M', '𑣎'), (0x118AF, 'M', '𑣏'), (0x118B0, 'M', '𑣐'), (0x118B1, 'M', '𑣑'), (0x118B2, 'M', '𑣒'), (0x118B3, 'M', '𑣓'), (0x118B4, 'M', '𑣔'), (0x118B5, 'M', '𑣕'), (0x118B6, 'M', '𑣖'), (0x118B7, 'M', '𑣗'), (0x118B8, 'M', '𑣘'), (0x118B9, 'M', '𑣙'), (0x118BA, 'M', '𑣚'), (0x118BB, 'M', '𑣛'), (0x118BC, 'M', '𑣜'), (0x118BD, 'M', '𑣝'), (0x118BE, 'M', '𑣞'), (0x118BF, 'M', '𑣟'), (0x118C0, 'V'), (0x118F3, 'X'), (0x118FF, 'V'), (0x11907, 'X'), (0x11909, 'V'), (0x1190A, 'X'), (0x1190C, 'V'), (0x11914, 'X'), (0x11915, 'V'), (0x11917, 'X'), (0x11918, 'V'), (0x11936, 'X'), (0x11937, 'V'), (0x11939, 'X'), (0x1193B, 'V'), (0x11947, 'X'), (0x11950, 'V'), (0x1195A, 'X'), (0x119A0, 'V'), (0x119A8, 'X'), (0x119AA, 'V'), (0x119D8, 'X'), (0x119DA, 'V'), (0x119E5, 'X'), (0x11A00, 'V'), (0x11A48, 'X'), (0x11A50, 'V'), (0x11AA3, 'X'), (0x11AB0, 'V'), (0x11AF9, 'X'), (0x11C00, 'V'), (0x11C09, 'X'), (0x11C0A, 'V'), (0x11C37, 'X'), (0x11C38, 'V'), (0x11C46, 'X'), (0x11C50, 'V'), (0x11C6D, 'X'), (0x11C70, 'V'), (0x11C90, 'X'), (0x11C92, 'V'), (0x11CA8, 'X'), (0x11CA9, 'V'), (0x11CB7, 'X'), (0x11D00, 'V'), (0x11D07, 'X'), (0x11D08, 'V'), (0x11D0A, 'X'), (0x11D0B, 'V'), (0x11D37, 'X'), (0x11D3A, 'V'), (0x11D3B, 'X'), (0x11D3C, 'V'), (0x11D3E, 'X'), (0x11D3F, 'V'), (0x11D48, 'X'), (0x11D50, 'V'), (0x11D5A, 'X'), (0x11D60, 'V'), (0x11D66, 'X'), (0x11D67, 'V'), (0x11D69, 'X'), (0x11D6A, 'V'), (0x11D8F, 'X'), (0x11D90, 'V'), (0x11D92, 'X'), (0x11D93, 'V'), (0x11D99, 'X'), (0x11DA0, 'V'), (0x11DAA, 'X'), (0x11EE0, 'V'), (0x11EF9, 'X'), (0x11FB0, 'V'), (0x11FB1, 'X'), (0x11FC0, 'V'), ] def _seg_59() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x11FF2, 'X'), (0x11FFF, 'V'), (0x1239A, 'X'), (0x12400, 'V'), (0x1246F, 'X'), (0x12470, 'V'), (0x12475, 'X'), (0x12480, 'V'), (0x12544, 'X'), (0x12F90, 'V'), (0x12FF3, 'X'), (0x13000, 'V'), (0x1342F, 'X'), (0x14400, 'V'), (0x14647, 'X'), (0x16800, 'V'), (0x16A39, 'X'), (0x16A40, 'V'), (0x16A5F, 'X'), (0x16A60, 'V'), (0x16A6A, 'X'), (0x16A6E, 'V'), (0x16ABF, 'X'), (0x16AC0, 'V'), (0x16ACA, 'X'), (0x16AD0, 'V'), (0x16AEE, 'X'), (0x16AF0, 'V'), (0x16AF6, 'X'), (0x16B00, 'V'), (0x16B46, 'X'), (0x16B50, 'V'), (0x16B5A, 'X'), (0x16B5B, 'V'), (0x16B62, 'X'), (0x16B63, 'V'), (0x16B78, 'X'), (0x16B7D, 'V'), (0x16B90, 'X'), (0x16E40, 'M', '𖹠'), (0x16E41, 'M', '𖹡'), (0x16E42, 'M', '𖹢'), (0x16E43, 'M', '𖹣'), (0x16E44, 'M', '𖹤'), (0x16E45, 'M', '𖹥'), (0x16E46, 'M', '𖹦'), (0x16E47, 'M', '𖹧'), (0x16E48, 'M', '𖹨'), (0x16E49, 'M', '𖹩'), (0x16E4A, 'M', '𖹪'), (0x16E4B, 'M', '𖹫'), (0x16E4C, 'M', '𖹬'), (0x16E4D, 'M', '𖹭'), (0x16E4E, 'M', '𖹮'), (0x16E4F, 'M', '𖹯'), (0x16E50, 'M', '𖹰'), (0x16E51, 'M', '𖹱'), (0x16E52, 'M', '𖹲'), (0x16E53, 'M', '𖹳'), (0x16E54, 'M', '𖹴'), (0x16E55, 'M', '𖹵'), (0x16E56, 'M', '𖹶'), (0x16E57, 'M', '𖹷'), (0x16E58, 'M', '𖹸'), (0x16E59, 'M', '𖹹'), (0x16E5A, 'M', '𖹺'), (0x16E5B, 'M', '𖹻'), (0x16E5C, 'M', '𖹼'), (0x16E5D, 'M', '𖹽'), (0x16E5E, 'M', '𖹾'), (0x16E5F, 'M', '𖹿'), (0x16E60, 'V'), (0x16E9B, 'X'), (0x16F00, 'V'), (0x16F4B, 'X'), (0x16F4F, 'V'), (0x16F88, 'X'), (0x16F8F, 'V'), (0x16FA0, 'X'), (0x16FE0, 'V'), (0x16FE5, 'X'), (0x16FF0, 'V'), (0x16FF2, 'X'), (0x17000, 'V'), (0x187F8, 'X'), (0x18800, 'V'), (0x18CD6, 'X'), (0x18D00, 'V'), (0x18D09, 'X'), (0x1AFF0, 'V'), (0x1AFF4, 'X'), (0x1AFF5, 'V'), (0x1AFFC, 'X'), (0x1AFFD, 'V'), (0x1AFFF, 'X'), (0x1B000, 'V'), (0x1B123, 'X'), (0x1B150, 'V'), (0x1B153, 'X'), (0x1B164, 'V'), ] def _seg_60() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1B168, 'X'), (0x1B170, 'V'), (0x1B2FC, 'X'), (0x1BC00, 'V'), (0x1BC6B, 'X'), (0x1BC70, 'V'), (0x1BC7D, 'X'), (0x1BC80, 'V'), (0x1BC89, 'X'), (0x1BC90, 'V'), (0x1BC9A, 'X'), (0x1BC9C, 'V'), (0x1BCA0, 'I'), (0x1BCA4, 'X'), (0x1CF00, 'V'), (0x1CF2E, 'X'), (0x1CF30, 'V'), (0x1CF47, 'X'), (0x1CF50, 'V'), (0x1CFC4, 'X'), (0x1D000, 'V'), (0x1D0F6, 'X'), (0x1D100, 'V'), (0x1D127, 'X'), (0x1D129, 'V'), (0x1D15E, 'M', '𝅗𝅥'), (0x1D15F, 'M', '𝅘𝅥'), (0x1D160, 'M', '𝅘𝅥𝅮'), (0x1D161, 'M', '𝅘𝅥𝅯'), (0x1D162, 'M', '𝅘𝅥𝅰'), (0x1D163, 'M', '𝅘𝅥𝅱'), (0x1D164, 'M', '𝅘𝅥𝅲'), (0x1D165, 'V'), (0x1D173, 'X'), (0x1D17B, 'V'), (0x1D1BB, 'M', '𝆹𝅥'), (0x1D1BC, 'M', '𝆺𝅥'), (0x1D1BD, 'M', '𝆹𝅥𝅮'), (0x1D1BE, 'M', '𝆺𝅥𝅮'), (0x1D1BF, 'M', '𝆹𝅥𝅯'), (0x1D1C0, 'M', '𝆺𝅥𝅯'), (0x1D1C1, 'V'), (0x1D1EB, 'X'), (0x1D200, 'V'), (0x1D246, 'X'), (0x1D2E0, 'V'), (0x1D2F4, 'X'), (0x1D300, 'V'), (0x1D357, 'X'), (0x1D360, 'V'), (0x1D379, 'X'), (0x1D400, 'M', 'a'), (0x1D401, 'M', 'b'), (0x1D402, 'M', 'c'), (0x1D403, 'M', 'd'), (0x1D404, 'M', 'e'), (0x1D405, 'M', 'f'), (0x1D406, 'M', 'g'), (0x1D407, 'M', 'h'), (0x1D408, 'M', 'i'), (0x1D409, 'M', 'j'), (0x1D40A, 'M', 'k'), (0x1D40B, 'M', 'l'), (0x1D40C, 'M', 'm'), (0x1D40D, 'M', 'n'), (0x1D40E, 'M', 'o'), (0x1D40F, 'M', 'p'), (0x1D410, 'M', 'q'), (0x1D411, 'M', 'r'), (0x1D412, 'M', 's'), (0x1D413, 'M', 't'), (0x1D414, 'M', 'u'), (0x1D415, 'M', 'v'), (0x1D416, 'M', 'w'), (0x1D417, 'M', 'x'), (0x1D418, 'M', 'y'), (0x1D419, 'M', 'z'), (0x1D41A, 'M', 'a'), (0x1D41B, 'M', 'b'), (0x1D41C, 'M', 'c'), (0x1D41D, 'M', 'd'), (0x1D41E, 'M', 'e'), (0x1D41F, 'M', 'f'), (0x1D420, 'M', 'g'), (0x1D421, 'M', 'h'), (0x1D422, 'M', 'i'), (0x1D423, 'M', 'j'), (0x1D424, 'M', 'k'), (0x1D425, 'M', 'l'), (0x1D426, 'M', 'm'), (0x1D427, 'M', 'n'), (0x1D428, 'M', 'o'), (0x1D429, 'M', 'p'), (0x1D42A, 'M', 'q'), (0x1D42B, 'M', 'r'), (0x1D42C, 'M', 's'), (0x1D42D, 'M', 't'), (0x1D42E, 'M', 'u'), (0x1D42F, 'M', 'v'), (0x1D430, 'M', 'w'), ] def _seg_61() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D431, 'M', 'x'), (0x1D432, 'M', 'y'), (0x1D433, 'M', 'z'), (0x1D434, 'M', 'a'), (0x1D435, 'M', 'b'), (0x1D436, 'M', 'c'), (0x1D437, 'M', 'd'), (0x1D438, 'M', 'e'), (0x1D439, 'M', 'f'), (0x1D43A, 'M', 'g'), (0x1D43B, 'M', 'h'), (0x1D43C, 'M', 'i'), (0x1D43D, 'M', 'j'), (0x1D43E, 'M', 'k'), (0x1D43F, 'M', 'l'), (0x1D440, 'M', 'm'), (0x1D441, 'M', 'n'), (0x1D442, 'M', 'o'), (0x1D443, 'M', 'p'), (0x1D444, 'M', 'q'), (0x1D445, 'M', 'r'), (0x1D446, 'M', 's'), (0x1D447, 'M', 't'), (0x1D448, 'M', 'u'), (0x1D449, 'M', 'v'), (0x1D44A, 'M', 'w'), (0x1D44B, 'M', 'x'), (0x1D44C, 'M', 'y'), (0x1D44D, 'M', 'z'), (0x1D44E, 'M', 'a'), (0x1D44F, 'M', 'b'), (0x1D450, 'M', 'c'), (0x1D451, 'M', 'd'), (0x1D452, 'M', 'e'), (0x1D453, 'M', 'f'), (0x1D454, 'M', 'g'), (0x1D455, 'X'), (0x1D456, 'M', 'i'), (0x1D457, 'M', 'j'), (0x1D458, 'M', 'k'), (0x1D459, 'M', 'l'), (0x1D45A, 'M', 'm'), (0x1D45B, 'M', 'n'), (0x1D45C, 'M', 'o'), (0x1D45D, 'M', 'p'), (0x1D45E, 'M', 'q'), (0x1D45F, 'M', 'r'), (0x1D460, 'M', 's'), (0x1D461, 'M', 't'), (0x1D462, 'M', 'u'), (0x1D463, 'M', 'v'), (0x1D464, 'M', 'w'), (0x1D465, 'M', 'x'), (0x1D466, 'M', 'y'), (0x1D467, 'M', 'z'), (0x1D468, 'M', 'a'), (0x1D469, 'M', 'b'), (0x1D46A, 'M', 'c'), (0x1D46B, 'M', 'd'), (0x1D46C, 'M', 'e'), (0x1D46D, 'M', 'f'), (0x1D46E, 'M', 'g'), (0x1D46F, 'M', 'h'), (0x1D470, 'M', 'i'), (0x1D471, 'M', 'j'), (0x1D472, 'M', 'k'), (0x1D473, 'M', 'l'), (0x1D474, 'M', 'm'), (0x1D475, 'M', 'n'), (0x1D476, 'M', 'o'), (0x1D477, 'M', 'p'), (0x1D478, 'M', 'q'), (0x1D479, 'M', 'r'), (0x1D47A, 'M', 's'), (0x1D47B, 'M', 't'), (0x1D47C, 'M', 'u'), (0x1D47D, 'M', 'v'), (0x1D47E, 'M', 'w'), (0x1D47F, 'M', 'x'), (0x1D480, 'M', 'y'), (0x1D481, 'M', 'z'), (0x1D482, 'M', 'a'), (0x1D483, 'M', 'b'), (0x1D484, 'M', 'c'), (0x1D485, 'M', 'd'), (0x1D486, 'M', 'e'), (0x1D487, 'M', 'f'), (0x1D488, 'M', 'g'), (0x1D489, 'M', 'h'), (0x1D48A, 'M', 'i'), (0x1D48B, 'M', 'j'), (0x1D48C, 'M', 'k'), (0x1D48D, 'M', 'l'), (0x1D48E, 'M', 'm'), (0x1D48F, 'M', 'n'), (0x1D490, 'M', 'o'), (0x1D491, 'M', 'p'), (0x1D492, 'M', 'q'), (0x1D493, 'M', 'r'), (0x1D494, 'M', 's'), ] def _seg_62() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D495, 'M', 't'), (0x1D496, 'M', 'u'), (0x1D497, 'M', 'v'), (0x1D498, 'M', 'w'), (0x1D499, 'M', 'x'), (0x1D49A, 'M', 'y'), (0x1D49B, 'M', 'z'), (0x1D49C, 'M', 'a'), (0x1D49D, 'X'), (0x1D49E, 'M', 'c'), (0x1D49F, 'M', 'd'), (0x1D4A0, 'X'), (0x1D4A2, 'M', 'g'), (0x1D4A3, 'X'), (0x1D4A5, 'M', 'j'), (0x1D4A6, 'M', 'k'), (0x1D4A7, 'X'), (0x1D4A9, 'M', 'n'), (0x1D4AA, 'M', 'o'), (0x1D4AB, 'M', 'p'), (0x1D4AC, 'M', 'q'), (0x1D4AD, 'X'), (0x1D4AE, 'M', 's'), (0x1D4AF, 'M', 't'), (0x1D4B0, 'M', 'u'), (0x1D4B1, 'M', 'v'), (0x1D4B2, 'M', 'w'), (0x1D4B3, 'M', 'x'), (0x1D4B4, 'M', 'y'), (0x1D4B5, 'M', 'z'), (0x1D4B6, 'M', 'a'), (0x1D4B7, 'M', 'b'), (0x1D4B8, 'M', 'c'), (0x1D4B9, 'M', 'd'), (0x1D4BA, 'X'), (0x1D4BB, 'M', 'f'), (0x1D4BC, 'X'), (0x1D4BD, 'M', 'h'), (0x1D4BE, 'M', 'i'), (0x1D4BF, 'M', 'j'), (0x1D4C0, 'M', 'k'), (0x1D4C1, 'M', 'l'), (0x1D4C2, 'M', 'm'), (0x1D4C3, 'M', 'n'), (0x1D4C4, 'X'), (0x1D4C5, 'M', 'p'), (0x1D4C6, 'M', 'q'), (0x1D4C7, 'M', 'r'), (0x1D4C8, 'M', 's'), (0x1D4C9, 'M', 't'), (0x1D4CA, 'M', 'u'), (0x1D4CB, 'M', 'v'), (0x1D4CC, 'M', 'w'), (0x1D4CD, 'M', 'x'), (0x1D4CE, 'M', 'y'), (0x1D4CF, 'M', 'z'), (0x1D4D0, 'M', 'a'), (0x1D4D1, 'M', 'b'), (0x1D4D2, 'M', 'c'), (0x1D4D3, 'M', 'd'), (0x1D4D4, 'M', 'e'), (0x1D4D5, 'M', 'f'), (0x1D4D6, 'M', 'g'), (0x1D4D7, 'M', 'h'), (0x1D4D8, 'M', 'i'), (0x1D4D9, 'M', 'j'), (0x1D4DA, 'M', 'k'), (0x1D4DB, 'M', 'l'), (0x1D4DC, 'M', 'm'), (0x1D4DD, 'M', 'n'), (0x1D4DE, 'M', 'o'), (0x1D4DF, 'M', 'p'), (0x1D4E0, 'M', 'q'), (0x1D4E1, 'M', 'r'), (0x1D4E2, 'M', 's'), (0x1D4E3, 'M', 't'), (0x1D4E4, 'M', 'u'), (0x1D4E5, 'M', 'v'), (0x1D4E6, 'M', 'w'), (0x1D4E7, 'M', 'x'), (0x1D4E8, 'M', 'y'), (0x1D4E9, 'M', 'z'), (0x1D4EA, 'M', 'a'), (0x1D4EB, 'M', 'b'), (0x1D4EC, 'M', 'c'), (0x1D4ED, 'M', 'd'), (0x1D4EE, 'M', 'e'), (0x1D4EF, 'M', 'f'), (0x1D4F0, 'M', 'g'), (0x1D4F1, 'M', 'h'), (0x1D4F2, 'M', 'i'), (0x1D4F3, 'M', 'j'), (0x1D4F4, 'M', 'k'), (0x1D4F5, 'M', 'l'), (0x1D4F6, 'M', 'm'), (0x1D4F7, 'M', 'n'), (0x1D4F8, 'M', 'o'), (0x1D4F9, 'M', 'p'), (0x1D4FA, 'M', 'q'), (0x1D4FB, 'M', 'r'), ] def _seg_63() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D4FC, 'M', 's'), (0x1D4FD, 'M', 't'), (0x1D4FE, 'M', 'u'), (0x1D4FF, 'M', 'v'), (0x1D500, 'M', 'w'), (0x1D501, 'M', 'x'), (0x1D502, 'M', 'y'), (0x1D503, 'M', 'z'), (0x1D504, 'M', 'a'), (0x1D505, 'M', 'b'), (0x1D506, 'X'), (0x1D507, 'M', 'd'), (0x1D508, 'M', 'e'), (0x1D509, 'M', 'f'), (0x1D50A, 'M', 'g'), (0x1D50B, 'X'), (0x1D50D, 'M', 'j'), (0x1D50E, 'M', 'k'), (0x1D50F, 'M', 'l'), (0x1D510, 'M', 'm'), (0x1D511, 'M', 'n'), (0x1D512, 'M', 'o'), (0x1D513, 'M', 'p'), (0x1D514, 'M', 'q'), (0x1D515, 'X'), (0x1D516, 'M', 's'), (0x1D517, 'M', 't'), (0x1D518, 'M', 'u'), (0x1D519, 'M', 'v'), (0x1D51A, 'M', 'w'), (0x1D51B, 'M', 'x'), (0x1D51C, 'M', 'y'), (0x1D51D, 'X'), (0x1D51E, 'M', 'a'), (0x1D51F, 'M', 'b'), (0x1D520, 'M', 'c'), (0x1D521, 'M', 'd'), (0x1D522, 'M', 'e'), (0x1D523, 'M', 'f'), (0x1D524, 'M', 'g'), (0x1D525, 'M', 'h'), (0x1D526, 'M', 'i'), (0x1D527, 'M', 'j'), (0x1D528, 'M', 'k'), (0x1D529, 'M', 'l'), (0x1D52A, 'M', 'm'), (0x1D52B, 'M', 'n'), (0x1D52C, 'M', 'o'), (0x1D52D, 'M', 'p'), (0x1D52E, 'M', 'q'), (0x1D52F, 'M', 'r'), (0x1D530, 'M', 's'), (0x1D531, 'M', 't'), (0x1D532, 'M', 'u'), (0x1D533, 'M', 'v'), (0x1D534, 'M', 'w'), (0x1D535, 'M', 'x'), (0x1D536, 'M', 'y'), (0x1D537, 'M', 'z'), (0x1D538, 'M', 'a'), (0x1D539, 'M', 'b'), (0x1D53A, 'X'), (0x1D53B, 'M', 'd'), (0x1D53C, 'M', 'e'), (0x1D53D, 'M', 'f'), (0x1D53E, 'M', 'g'), (0x1D53F, 'X'), (0x1D540, 'M', 'i'), (0x1D541, 'M', 'j'), (0x1D542, 'M', 'k'), (0x1D543, 'M', 'l'), (0x1D544, 'M', 'm'), (0x1D545, 'X'), (0x1D546, 'M', 'o'), (0x1D547, 'X'), (0x1D54A, 'M', 's'), (0x1D54B, 'M', 't'), (0x1D54C, 'M', 'u'), (0x1D54D, 'M', 'v'), (0x1D54E, 'M', 'w'), (0x1D54F, 'M', 'x'), (0x1D550, 'M', 'y'), (0x1D551, 'X'), (0x1D552, 'M', 'a'), (0x1D553, 'M', 'b'), (0x1D554, 'M', 'c'), (0x1D555, 'M', 'd'), (0x1D556, 'M', 'e'), (0x1D557, 'M', 'f'), (0x1D558, 'M', 'g'), (0x1D559, 'M', 'h'), (0x1D55A, 'M', 'i'), (0x1D55B, 'M', 'j'), (0x1D55C, 'M', 'k'), (0x1D55D, 'M', 'l'), (0x1D55E, 'M', 'm'), (0x1D55F, 'M', 'n'), (0x1D560, 'M', 'o'), (0x1D561, 'M', 'p'), (0x1D562, 'M', 'q'), ] def _seg_64() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D563, 'M', 'r'), (0x1D564, 'M', 's'), (0x1D565, 'M', 't'), (0x1D566, 'M', 'u'), (0x1D567, 'M', 'v'), (0x1D568, 'M', 'w'), (0x1D569, 'M', 'x'), (0x1D56A, 'M', 'y'), (0x1D56B, 'M', 'z'), (0x1D56C, 'M', 'a'), (0x1D56D, 'M', 'b'), (0x1D56E, 'M', 'c'), (0x1D56F, 'M', 'd'), (0x1D570, 'M', 'e'), (0x1D571, 'M', 'f'), (0x1D572, 'M', 'g'), (0x1D573, 'M', 'h'), (0x1D574, 'M', 'i'), (0x1D575, 'M', 'j'), (0x1D576, 'M', 'k'), (0x1D577, 'M', 'l'), (0x1D578, 'M', 'm'), (0x1D579, 'M', 'n'), (0x1D57A, 'M', 'o'), (0x1D57B, 'M', 'p'), (0x1D57C, 'M', 'q'), (0x1D57D, 'M', 'r'), (0x1D57E, 'M', 's'), (0x1D57F, 'M', 't'), (0x1D580, 'M', 'u'), (0x1D581, 'M', 'v'), (0x1D582, 'M', 'w'), (0x1D583, 'M', 'x'), (0x1D584, 'M', 'y'), (0x1D585, 'M', 'z'), (0x1D586, 'M', 'a'), (0x1D587, 'M', 'b'), (0x1D588, 'M', 'c'), (0x1D589, 'M', 'd'), (0x1D58A, 'M', 'e'), (0x1D58B, 'M', 'f'), (0x1D58C, 'M', 'g'), (0x1D58D, 'M', 'h'), (0x1D58E, 'M', 'i'), (0x1D58F, 'M', 'j'), (0x1D590, 'M', 'k'), (0x1D591, 'M', 'l'), (0x1D592, 'M', 'm'), (0x1D593, 'M', 'n'), (0x1D594, 'M', 'o'), (0x1D595, 'M', 'p'), (0x1D596, 'M', 'q'), (0x1D597, 'M', 'r'), (0x1D598, 'M', 's'), (0x1D599, 'M', 't'), (0x1D59A, 'M', 'u'), (0x1D59B, 'M', 'v'), (0x1D59C, 'M', 'w'), (0x1D59D, 'M', 'x'), (0x1D59E, 'M', 'y'), (0x1D59F, 'M', 'z'), (0x1D5A0, 'M', 'a'), (0x1D5A1, 'M', 'b'), (0x1D5A2, 'M', 'c'), (0x1D5A3, 'M', 'd'), (0x1D5A4, 'M', 'e'), (0x1D5A5, 'M', 'f'), (0x1D5A6, 'M', 'g'), (0x1D5A7, 'M', 'h'), (0x1D5A8, 'M', 'i'), (0x1D5A9, 'M', 'j'), (0x1D5AA, 'M', 'k'), (0x1D5AB, 'M', 'l'), (0x1D5AC, 'M', 'm'), (0x1D5AD, 'M', 'n'), (0x1D5AE, 'M', 'o'), (0x1D5AF, 'M', 'p'), (0x1D5B0, 'M', 'q'), (0x1D5B1, 'M', 'r'), (0x1D5B2, 'M', 's'), (0x1D5B3, 'M', 't'), (0x1D5B4, 'M', 'u'), (0x1D5B5, 'M', 'v'), (0x1D5B6, 'M', 'w'), (0x1D5B7, 'M', 'x'), (0x1D5B8, 'M', 'y'), (0x1D5B9, 'M', 'z'), (0x1D5BA, 'M', 'a'), (0x1D5BB, 'M', 'b'), (0x1D5BC, 'M', 'c'), (0x1D5BD, 'M', 'd'), (0x1D5BE, 'M', 'e'), (0x1D5BF, 'M', 'f'), (0x1D5C0, 'M', 'g'), (0x1D5C1, 'M', 'h'), (0x1D5C2, 'M', 'i'), (0x1D5C3, 'M', 'j'), (0x1D5C4, 'M', 'k'), (0x1D5C5, 'M', 'l'), (0x1D5C6, 'M', 'm'), ] def _seg_65() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D5C7, 'M', 'n'), (0x1D5C8, 'M', 'o'), (0x1D5C9, 'M', 'p'), (0x1D5CA, 'M', 'q'), (0x1D5CB, 'M', 'r'), (0x1D5CC, 'M', 's'), (0x1D5CD, 'M', 't'), (0x1D5CE, 'M', 'u'), (0x1D5CF, 'M', 'v'), (0x1D5D0, 'M', 'w'), (0x1D5D1, 'M', 'x'), (0x1D5D2, 'M', 'y'), (0x1D5D3, 'M', 'z'), (0x1D5D4, 'M', 'a'), (0x1D5D5, 'M', 'b'), (0x1D5D6, 'M', 'c'), (0x1D5D7, 'M', 'd'), (0x1D5D8, 'M', 'e'), (0x1D5D9, 'M', 'f'), (0x1D5DA, 'M', 'g'), (0x1D5DB, 'M', 'h'), (0x1D5DC, 'M', 'i'), (0x1D5DD, 'M', 'j'), (0x1D5DE, 'M', 'k'), (0x1D5DF, 'M', 'l'), (0x1D5E0, 'M', 'm'), (0x1D5E1, 'M', 'n'), (0x1D5E2, 'M', 'o'), (0x1D5E3, 'M', 'p'), (0x1D5E4, 'M', 'q'), (0x1D5E5, 'M', 'r'), (0x1D5E6, 'M', 's'), (0x1D5E7, 'M', 't'), (0x1D5E8, 'M', 'u'), (0x1D5E9, 'M', 'v'), (0x1D5EA, 'M', 'w'), (0x1D5EB, 'M', 'x'), (0x1D5EC, 'M', 'y'), (0x1D5ED, 'M', 'z'), (0x1D5EE, 'M', 'a'), (0x1D5EF, 'M', 'b'), (0x1D5F0, 'M', 'c'), (0x1D5F1, 'M', 'd'), (0x1D5F2, 'M', 'e'), (0x1D5F3, 'M', 'f'), (0x1D5F4, 'M', 'g'), (0x1D5F5, 'M', 'h'), (0x1D5F6, 'M', 'i'), (0x1D5F7, 'M', 'j'), (0x1D5F8, 'M', 'k'), (0x1D5F9, 'M', 'l'), (0x1D5FA, 'M', 'm'), (0x1D5FB, 'M', 'n'), (0x1D5FC, 'M', 'o'), (0x1D5FD, 'M', 'p'), (0x1D5FE, 'M', 'q'), (0x1D5FF, 'M', 'r'), (0x1D600, 'M', 's'), (0x1D601, 'M', 't'), (0x1D602, 'M', 'u'), (0x1D603, 'M', 'v'), (0x1D604, 'M', 'w'), (0x1D605, 'M', 'x'), (0x1D606, 'M', 'y'), (0x1D607, 'M', 'z'), (0x1D608, 'M', 'a'), (0x1D609, 'M', 'b'), (0x1D60A, 'M', 'c'), (0x1D60B, 'M', 'd'), (0x1D60C, 'M', 'e'), (0x1D60D, 'M', 'f'), (0x1D60E, 'M', 'g'), (0x1D60F, 'M', 'h'), (0x1D610, 'M', 'i'), (0x1D611, 'M', 'j'), (0x1D612, 'M', 'k'), (0x1D613, 'M', 'l'), (0x1D614, 'M', 'm'), (0x1D615, 'M', 'n'), (0x1D616, 'M', 'o'), (0x1D617, 'M', 'p'), (0x1D618, 'M', 'q'), (0x1D619, 'M', 'r'), (0x1D61A, 'M', 's'), (0x1D61B, 'M', 't'), (0x1D61C, 'M', 'u'), (0x1D61D, 'M', 'v'), (0x1D61E, 'M', 'w'), (0x1D61F, 'M', 'x'), (0x1D620, 'M', 'y'), (0x1D621, 'M', 'z'), (0x1D622, 'M', 'a'), (0x1D623, 'M', 'b'), (0x1D624, 'M', 'c'), (0x1D625, 'M', 'd'), (0x1D626, 'M', 'e'), (0x1D627, 'M', 'f'), (0x1D628, 'M', 'g'), (0x1D629, 'M', 'h'), (0x1D62A, 'M', 'i'), ] def _seg_66() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D62B, 'M', 'j'), (0x1D62C, 'M', 'k'), (0x1D62D, 'M', 'l'), (0x1D62E, 'M', 'm'), (0x1D62F, 'M', 'n'), (0x1D630, 'M', 'o'), (0x1D631, 'M', 'p'), (0x1D632, 'M', 'q'), (0x1D633, 'M', 'r'), (0x1D634, 'M', 's'), (0x1D635, 'M', 't'), (0x1D636, 'M', 'u'), (0x1D637, 'M', 'v'), (0x1D638, 'M', 'w'), (0x1D639, 'M', 'x'), (0x1D63A, 'M', 'y'), (0x1D63B, 'M', 'z'), (0x1D63C, 'M', 'a'), (0x1D63D, 'M', 'b'), (0x1D63E, 'M', 'c'), (0x1D63F, 'M', 'd'), (0x1D640, 'M', 'e'), (0x1D641, 'M', 'f'), (0x1D642, 'M', 'g'), (0x1D643, 'M', 'h'), (0x1D644, 'M', 'i'), (0x1D645, 'M', 'j'), (0x1D646, 'M', 'k'), (0x1D647, 'M', 'l'), (0x1D648, 'M', 'm'), (0x1D649, 'M', 'n'), (0x1D64A, 'M', 'o'), (0x1D64B, 'M', 'p'), (0x1D64C, 'M', 'q'), (0x1D64D, 'M', 'r'), (0x1D64E, 'M', 's'), (0x1D64F, 'M', 't'), (0x1D650, 'M', 'u'), (0x1D651, 'M', 'v'), (0x1D652, 'M', 'w'), (0x1D653, 'M', 'x'), (0x1D654, 'M', 'y'), (0x1D655, 'M', 'z'), (0x1D656, 'M', 'a'), (0x1D657, 'M', 'b'), (0x1D658, 'M', 'c'), (0x1D659, 'M', 'd'), (0x1D65A, 'M', 'e'), (0x1D65B, 'M', 'f'), (0x1D65C, 'M', 'g'), (0x1D65D, 'M', 'h'), (0x1D65E, 'M', 'i'), (0x1D65F, 'M', 'j'), (0x1D660, 'M', 'k'), (0x1D661, 'M', 'l'), (0x1D662, 'M', 'm'), (0x1D663, 'M', 'n'), (0x1D664, 'M', 'o'), (0x1D665, 'M', 'p'), (0x1D666, 'M', 'q'), (0x1D667, 'M', 'r'), (0x1D668, 'M', 's'), (0x1D669, 'M', 't'), (0x1D66A, 'M', 'u'), (0x1D66B, 'M', 'v'), (0x1D66C, 'M', 'w'), (0x1D66D, 'M', 'x'), (0x1D66E, 'M', 'y'), (0x1D66F, 'M', 'z'), (0x1D670, 'M', 'a'), (0x1D671, 'M', 'b'), (0x1D672, 'M', 'c'), (0x1D673, 'M', 'd'), (0x1D674, 'M', 'e'), (0x1D675, 'M', 'f'), (0x1D676, 'M', 'g'), (0x1D677, 'M', 'h'), (0x1D678, 'M', 'i'), (0x1D679, 'M', 'j'), (0x1D67A, 'M', 'k'), (0x1D67B, 'M', 'l'), (0x1D67C, 'M', 'm'), (0x1D67D, 'M', 'n'), (0x1D67E, 'M', 'o'), (0x1D67F, 'M', 'p'), (0x1D680, 'M', 'q'), (0x1D681, 'M', 'r'), (0x1D682, 'M', 's'), (0x1D683, 'M', 't'), (0x1D684, 'M', 'u'), (0x1D685, 'M', 'v'), (0x1D686, 'M', 'w'), (0x1D687, 'M', 'x'), (0x1D688, 'M', 'y'), (0x1D689, 'M', 'z'), (0x1D68A, 'M', 'a'), (0x1D68B, 'M', 'b'), (0x1D68C, 'M', 'c'), (0x1D68D, 'M', 'd'), (0x1D68E, 'M', 'e'), ] def _seg_67() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D68F, 'M', 'f'), (0x1D690, 'M', 'g'), (0x1D691, 'M', 'h'), (0x1D692, 'M', 'i'), (0x1D693, 'M', 'j'), (0x1D694, 'M', 'k'), (0x1D695, 'M', 'l'), (0x1D696, 'M', 'm'), (0x1D697, 'M', 'n'), (0x1D698, 'M', 'o'), (0x1D699, 'M', 'p'), (0x1D69A, 'M', 'q'), (0x1D69B, 'M', 'r'), (0x1D69C, 'M', 's'), (0x1D69D, 'M', 't'), (0x1D69E, 'M', 'u'), (0x1D69F, 'M', 'v'), (0x1D6A0, 'M', 'w'), (0x1D6A1, 'M', 'x'), (0x1D6A2, 'M', 'y'), (0x1D6A3, 'M', 'z'), (0x1D6A4, 'M', 'ı'), (0x1D6A5, 'M', 'ȷ'), (0x1D6A6, 'X'), (0x1D6A8, 'M', 'α'), (0x1D6A9, 'M', 'β'), (0x1D6AA, 'M', 'γ'), (0x1D6AB, 'M', 'δ'), (0x1D6AC, 'M', 'ε'), (0x1D6AD, 'M', 'ζ'), (0x1D6AE, 'M', 'η'), (0x1D6AF, 'M', 'θ'), (0x1D6B0, 'M', 'ι'), (0x1D6B1, 'M', 'κ'), (0x1D6B2, 'M', 'λ'), (0x1D6B3, 'M', 'μ'), (0x1D6B4, 'M', 'ν'), (0x1D6B5, 'M', 'ξ'), (0x1D6B6, 'M', 'ο'), (0x1D6B7, 'M', 'π'), (0x1D6B8, 'M', 'ρ'), (0x1D6B9, 'M', 'θ'), (0x1D6BA, 'M', 'σ'), (0x1D6BB, 'M', 'τ'), (0x1D6BC, 'M', 'υ'), (0x1D6BD, 'M', 'φ'), (0x1D6BE, 'M', 'χ'), (0x1D6BF, 'M', 'ψ'), (0x1D6C0, 'M', 'ω'), (0x1D6C1, 'M', '∇'), (0x1D6C2, 'M', 'α'), (0x1D6C3, 'M', 'β'), (0x1D6C4, 'M', 'γ'), (0x1D6C5, 'M', 'δ'), (0x1D6C6, 'M', 'ε'), (0x1D6C7, 'M', 'ζ'), (0x1D6C8, 'M', 'η'), (0x1D6C9, 'M', 'θ'), (0x1D6CA, 'M', 'ι'), (0x1D6CB, 'M', 'κ'), (0x1D6CC, 'M', 'λ'), (0x1D6CD, 'M', 'μ'), (0x1D6CE, 'M', 'ν'), (0x1D6CF, 'M', 'ξ'), (0x1D6D0, 'M', 'ο'), (0x1D6D1, 'M', 'π'), (0x1D6D2, 'M', 'ρ'), (0x1D6D3, 'M', 'σ'), (0x1D6D5, 'M', 'τ'), (0x1D6D6, 'M', 'υ'), (0x1D6D7, 'M', 'φ'), (0x1D6D8, 'M', 'χ'), (0x1D6D9, 'M', 'ψ'), (0x1D6DA, 'M', 'ω'), (0x1D6DB, 'M', '∂'), (0x1D6DC, 'M', 'ε'), (0x1D6DD, 'M', 'θ'), (0x1D6DE, 'M', 'κ'), (0x1D6DF, 'M', 'φ'), (0x1D6E0, 'M', 'ρ'), (0x1D6E1, 'M', 'π'), (0x1D6E2, 'M', 'α'), (0x1D6E3, 'M', 'β'), (0x1D6E4, 'M', 'γ'), (0x1D6E5, 'M', 'δ'), (0x1D6E6, 'M', 'ε'), (0x1D6E7, 'M', 'ζ'), (0x1D6E8, 'M', 'η'), (0x1D6E9, 'M', 'θ'), (0x1D6EA, 'M', 'ι'), (0x1D6EB, 'M', 'κ'), (0x1D6EC, 'M', 'λ'), (0x1D6ED, 'M', 'μ'), (0x1D6EE, 'M', 'ν'), (0x1D6EF, 'M', 'ξ'), (0x1D6F0, 'M', 'ο'), (0x1D6F1, 'M', 'π'), (0x1D6F2, 'M', 'ρ'), (0x1D6F3, 'M', 'θ'), (0x1D6F4, 'M', 'σ'), ] def _seg_68() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D6F5, 'M', 'τ'), (0x1D6F6, 'M', 'υ'), (0x1D6F7, 'M', 'φ'), (0x1D6F8, 'M', 'χ'), (0x1D6F9, 'M', 'ψ'), (0x1D6FA, 'M', 'ω'), (0x1D6FB, 'M', '∇'), (0x1D6FC, 'M', 'α'), (0x1D6FD, 'M', 'β'), (0x1D6FE, 'M', 'γ'), (0x1D6FF, 'M', 'δ'), (0x1D700, 'M', 'ε'), (0x1D701, 'M', 'ζ'), (0x1D702, 'M', 'η'), (0x1D703, 'M', 'θ'), (0x1D704, 'M', 'ι'), (0x1D705, 'M', 'κ'), (0x1D706, 'M', 'λ'), (0x1D707, 'M', 'μ'), (0x1D708, 'M', 'ν'), (0x1D709, 'M', 'ξ'), (0x1D70A, 'M', 'ο'), (0x1D70B, 'M', 'π'), (0x1D70C, 'M', 'ρ'), (0x1D70D, 'M', 'σ'), (0x1D70F, 'M', 'τ'), (0x1D710, 'M', 'υ'), (0x1D711, 'M', 'φ'), (0x1D712, 'M', 'χ'), (0x1D713, 'M', 'ψ'), (0x1D714, 'M', 'ω'), (0x1D715, 'M', '∂'), (0x1D716, 'M', 'ε'), (0x1D717, 'M', 'θ'), (0x1D718, 'M', 'κ'), (0x1D719, 'M', 'φ'), (0x1D71A, 'M', 'ρ'), (0x1D71B, 'M', 'π'), (0x1D71C, 'M', 'α'), (0x1D71D, 'M', 'β'), (0x1D71E, 'M', 'γ'), (0x1D71F, 'M', 'δ'), (0x1D720, 'M', 'ε'), (0x1D721, 'M', 'ζ'), (0x1D722, 'M', 'η'), (0x1D723, 'M', 'θ'), (0x1D724, 'M', 'ι'), (0x1D725, 'M', 'κ'), (0x1D726, 'M', 'λ'), (0x1D727, 'M', 'μ'), (0x1D728, 'M', 'ν'), (0x1D729, 'M', 'ξ'), (0x1D72A, 'M', 'ο'), (0x1D72B, 'M', 'π'), (0x1D72C, 'M', 'ρ'), (0x1D72D, 'M', 'θ'), (0x1D72E, 'M', 'σ'), (0x1D72F, 'M', 'τ'), (0x1D730, 'M', 'υ'), (0x1D731, 'M', 'φ'), (0x1D732, 'M', 'χ'), (0x1D733, 'M', 'ψ'), (0x1D734, 'M', 'ω'), (0x1D735, 'M', '∇'), (0x1D736, 'M', 'α'), (0x1D737, 'M', 'β'), (0x1D738, 'M', 'γ'), (0x1D739, 'M', 'δ'), (0x1D73A, 'M', 'ε'), (0x1D73B, 'M', 'ζ'), (0x1D73C, 'M', 'η'), (0x1D73D, 'M', 'θ'), (0x1D73E, 'M', 'ι'), (0x1D73F, 'M', 'κ'), (0x1D740, 'M', 'λ'), (0x1D741, 'M', 'μ'), (0x1D742, 'M', 'ν'), (0x1D743, 'M', 'ξ'), (0x1D744, 'M', 'ο'), (0x1D745, 'M', 'π'), (0x1D746, 'M', 'ρ'), (0x1D747, 'M', 'σ'), (0x1D749, 'M', 'τ'), (0x1D74A, 'M', 'υ'), (0x1D74B, 'M', 'φ'), (0x1D74C, 'M', 'χ'), (0x1D74D, 'M', 'ψ'), (0x1D74E, 'M', 'ω'), (0x1D74F, 'M', '∂'), (0x1D750, 'M', 'ε'), (0x1D751, 'M', 'θ'), (0x1D752, 'M', 'κ'), (0x1D753, 'M', 'φ'), (0x1D754, 'M', 'ρ'), (0x1D755, 'M', 'π'), (0x1D756, 'M', 'α'), (0x1D757, 'M', 'β'), (0x1D758, 'M', 'γ'), (0x1D759, 'M', 'δ'), (0x1D75A, 'M', 'ε'), ] def _seg_69() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D75B, 'M', 'ζ'), (0x1D75C, 'M', 'η'), (0x1D75D, 'M', 'θ'), (0x1D75E, 'M', 'ι'), (0x1D75F, 'M', 'κ'), (0x1D760, 'M', 'λ'), (0x1D761, 'M', 'μ'), (0x1D762, 'M', 'ν'), (0x1D763, 'M', 'ξ'), (0x1D764, 'M', 'ο'), (0x1D765, 'M', 'π'), (0x1D766, 'M', 'ρ'), (0x1D767, 'M', 'θ'), (0x1D768, 'M', 'σ'), (0x1D769, 'M', 'τ'), (0x1D76A, 'M', 'υ'), (0x1D76B, 'M', 'φ'), (0x1D76C, 'M', 'χ'), (0x1D76D, 'M', 'ψ'), (0x1D76E, 'M', 'ω'), (0x1D76F, 'M', '∇'), (0x1D770, 'M', 'α'), (0x1D771, 'M', 'β'), (0x1D772, 'M', 'γ'), (0x1D773, 'M', 'δ'), (0x1D774, 'M', 'ε'), (0x1D775, 'M', 'ζ'), (0x1D776, 'M', 'η'), (0x1D777, 'M', 'θ'), (0x1D778, 'M', 'ι'), (0x1D779, 'M', 'κ'), (0x1D77A, 'M', 'λ'), (0x1D77B, 'M', 'μ'), (0x1D77C, 'M', 'ν'), (0x1D77D, 'M', 'ξ'), (0x1D77E, 'M', 'ο'), (0x1D77F, 'M', 'π'), (0x1D780, 'M', 'ρ'), (0x1D781, 'M', 'σ'), (0x1D783, 'M', 'τ'), (0x1D784, 'M', 'υ'), (0x1D785, 'M', 'φ'), (0x1D786, 'M', 'χ'), (0x1D787, 'M', 'ψ'), (0x1D788, 'M', 'ω'), (0x1D789, 'M', '∂'), (0x1D78A, 'M', 'ε'), (0x1D78B, 'M', 'θ'), (0x1D78C, 'M', 'κ'), (0x1D78D, 'M', 'φ'), (0x1D78E, 'M', 'ρ'), (0x1D78F, 'M', 'π'), (0x1D790, 'M', 'α'), (0x1D791, 'M', 'β'), (0x1D792, 'M', 'γ'), (0x1D793, 'M', 'δ'), (0x1D794, 'M', 'ε'), (0x1D795, 'M', 'ζ'), (0x1D796, 'M', 'η'), (0x1D797, 'M', 'θ'), (0x1D798, 'M', 'ι'), (0x1D799, 'M', 'κ'), (0x1D79A, 'M', 'λ'), (0x1D79B, 'M', 'μ'), (0x1D79C, 'M', 'ν'), (0x1D79D, 'M', 'ξ'), (0x1D79E, 'M', 'ο'), (0x1D79F, 'M', 'π'), (0x1D7A0, 'M', 'ρ'), (0x1D7A1, 'M', 'θ'), (0x1D7A2, 'M', 'σ'), (0x1D7A3, 'M', 'τ'), (0x1D7A4, 'M', 'υ'), (0x1D7A5, 'M', 'φ'), (0x1D7A6, 'M', 'χ'), (0x1D7A7, 'M', 'ψ'), (0x1D7A8, 'M', 'ω'), (0x1D7A9, 'M', '∇'), (0x1D7AA, 'M', 'α'), (0x1D7AB, 'M', 'β'), (0x1D7AC, 'M', 'γ'), (0x1D7AD, 'M', 'δ'), (0x1D7AE, 'M', 'ε'), (0x1D7AF, 'M', 'ζ'), (0x1D7B0, 'M', 'η'), (0x1D7B1, 'M', 'θ'), (0x1D7B2, 'M', 'ι'), (0x1D7B3, 'M', 'κ'), (0x1D7B4, 'M', 'λ'), (0x1D7B5, 'M', 'μ'), (0x1D7B6, 'M', 'ν'), (0x1D7B7, 'M', 'ξ'), (0x1D7B8, 'M', 'ο'), (0x1D7B9, 'M', 'π'), (0x1D7BA, 'M', 'ρ'), (0x1D7BB, 'M', 'σ'), (0x1D7BD, 'M', 'τ'), (0x1D7BE, 'M', 'υ'), (0x1D7BF, 'M', 'φ'), (0x1D7C0, 'M', 'χ'), ] def _seg_70() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D7C1, 'M', 'ψ'), (0x1D7C2, 'M', 'ω'), (0x1D7C3, 'M', '∂'), (0x1D7C4, 'M', 'ε'), (0x1D7C5, 'M', 'θ'), (0x1D7C6, 'M', 'κ'), (0x1D7C7, 'M', 'φ'), (0x1D7C8, 'M', 'ρ'), (0x1D7C9, 'M', 'π'), (0x1D7CA, 'M', 'ϝ'), (0x1D7CC, 'X'), (0x1D7CE, 'M', '0'), (0x1D7CF, 'M', '1'), (0x1D7D0, 'M', '2'), (0x1D7D1, 'M', '3'), (0x1D7D2, 'M', '4'), (0x1D7D3, 'M', '5'), (0x1D7D4, 'M', '6'), (0x1D7D5, 'M', '7'), (0x1D7D6, 'M', '8'), (0x1D7D7, 'M', '9'), (0x1D7D8, 'M', '0'), (0x1D7D9, 'M', '1'), (0x1D7DA, 'M', '2'), (0x1D7DB, 'M', '3'), (0x1D7DC, 'M', '4'), (0x1D7DD, 'M', '5'), (0x1D7DE, 'M', '6'), (0x1D7DF, 'M', '7'), (0x1D7E0, 'M', '8'), (0x1D7E1, 'M', '9'), (0x1D7E2, 'M', '0'), (0x1D7E3, 'M', '1'), (0x1D7E4, 'M', '2'), (0x1D7E5, 'M', '3'), (0x1D7E6, 'M', '4'), (0x1D7E7, 'M', '5'), (0x1D7E8, 'M', '6'), (0x1D7E9, 'M', '7'), (0x1D7EA, 'M', '8'), (0x1D7EB, 'M', '9'), (0x1D7EC, 'M', '0'), (0x1D7ED, 'M', '1'), (0x1D7EE, 'M', '2'), (0x1D7EF, 'M', '3'), (0x1D7F0, 'M', '4'), (0x1D7F1, 'M', '5'), (0x1D7F2, 'M', '6'), (0x1D7F3, 'M', '7'), (0x1D7F4, 'M', '8'), (0x1D7F5, 'M', '9'), (0x1D7F6, 'M', '0'), (0x1D7F7, 'M', '1'), (0x1D7F8, 'M', '2'), (0x1D7F9, 'M', '3'), (0x1D7FA, 'M', '4'), (0x1D7FB, 'M', '5'), (0x1D7FC, 'M', '6'), (0x1D7FD, 'M', '7'), (0x1D7FE, 'M', '8'), (0x1D7FF, 'M', '9'), (0x1D800, 'V'), (0x1DA8C, 'X'), (0x1DA9B, 'V'), (0x1DAA0, 'X'), (0x1DAA1, 'V'), (0x1DAB0, 'X'), (0x1DF00, 'V'), (0x1DF1F, 'X'), (0x1E000, 'V'), (0x1E007, 'X'), (0x1E008, 'V'), (0x1E019, 'X'), (0x1E01B, 'V'), (0x1E022, 'X'), (0x1E023, 'V'), (0x1E025, 'X'), (0x1E026, 'V'), (0x1E02B, 'X'), (0x1E100, 'V'), (0x1E12D, 'X'), (0x1E130, 'V'), (0x1E13E, 'X'), (0x1E140, 'V'), (0x1E14A, 'X'), (0x1E14E, 'V'), (0x1E150, 'X'), (0x1E290, 'V'), (0x1E2AF, 'X'), (0x1E2C0, 'V'), (0x1E2FA, 'X'), (0x1E2FF, 'V'), (0x1E300, 'X'), (0x1E7E0, 'V'), (0x1E7E7, 'X'), (0x1E7E8, 'V'), (0x1E7EC, 'X'), (0x1E7ED, 'V'), (0x1E7EF, 'X'), (0x1E7F0, 'V'), ] def _seg_71() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1E7FF, 'X'), (0x1E800, 'V'), (0x1E8C5, 'X'), (0x1E8C7, 'V'), (0x1E8D7, 'X'), (0x1E900, 'M', '𞤢'), (0x1E901, 'M', '𞤣'), (0x1E902, 'M', '𞤤'), (0x1E903, 'M', '𞤥'), (0x1E904, 'M', '𞤦'), (0x1E905, 'M', '𞤧'), (0x1E906, 'M', '𞤨'), (0x1E907, 'M', '𞤩'), (0x1E908, 'M', '𞤪'), (0x1E909, 'M', '𞤫'), (0x1E90A, 'M', '𞤬'), (0x1E90B, 'M', '𞤭'), (0x1E90C, 'M', '𞤮'), (0x1E90D, 'M', '𞤯'), (0x1E90E, 'M', '𞤰'), (0x1E90F, 'M', '𞤱'), (0x1E910, 'M', '𞤲'), (0x1E911, 'M', '𞤳'), (0x1E912, 'M', '𞤴'), (0x1E913, 'M', '𞤵'), (0x1E914, 'M', '𞤶'), (0x1E915, 'M', '𞤷'), (0x1E916, 'M', '𞤸'), (0x1E917, 'M', '𞤹'), (0x1E918, 'M', '𞤺'), (0x1E919, 'M', '𞤻'), (0x1E91A, 'M', '𞤼'), (0x1E91B, 'M', '𞤽'), (0x1E91C, 'M', '𞤾'), (0x1E91D, 'M', '𞤿'), (0x1E91E, 'M', '𞥀'), (0x1E91F, 'M', '𞥁'), (0x1E920, 'M', '𞥂'), (0x1E921, 'M', '𞥃'), (0x1E922, 'V'), (0x1E94C, 'X'), (0x1E950, 'V'), (0x1E95A, 'X'), (0x1E95E, 'V'), (0x1E960, 'X'), (0x1EC71, 'V'), (0x1ECB5, 'X'), (0x1ED01, 'V'), (0x1ED3E, 'X'), (0x1EE00, 'M', 'ا'), (0x1EE01, 'M', 'ب'), (0x1EE02, 'M', 'ج'), (0x1EE03, 'M', 'د'), (0x1EE04, 'X'), (0x1EE05, 'M', 'و'), (0x1EE06, 'M', 'ز'), (0x1EE07, 'M', 'ح'), (0x1EE08, 'M', 'ط'), (0x1EE09, 'M', 'ي'), (0x1EE0A, 'M', 'ك'), (0x1EE0B, 'M', 'ل'), (0x1EE0C, 'M', 'م'), (0x1EE0D, 'M', 'ن'), (0x1EE0E, 'M', 'س'), (0x1EE0F, 'M', 'ع'), (0x1EE10, 'M', 'ف'), (0x1EE11, 'M', 'ص'), (0x1EE12, 'M', 'ق'), (0x1EE13, 'M', 'ر'), (0x1EE14, 'M', 'ش'), (0x1EE15, 'M', 'ت'), (0x1EE16, 'M', 'ث'), (0x1EE17, 'M', 'خ'), (0x1EE18, 'M', 'ذ'), (0x1EE19, 'M', 'ض'), (0x1EE1A, 'M', 'ظ'), (0x1EE1B, 'M', 'غ'), (0x1EE1C, 'M', 'ٮ'), (0x1EE1D, 'M', 'ں'), (0x1EE1E, 'M', 'ڡ'), (0x1EE1F, 'M', 'ٯ'), (0x1EE20, 'X'), (0x1EE21, 'M', 'ب'), (0x1EE22, 'M', 'ج'), (0x1EE23, 'X'), (0x1EE24, 'M', 'ه'), (0x1EE25, 'X'), (0x1EE27, 'M', 'ح'), (0x1EE28, 'X'), (0x1EE29, 'M', 'ي'), (0x1EE2A, 'M', 'ك'), (0x1EE2B, 'M', 'ل'), (0x1EE2C, 'M', 'م'), (0x1EE2D, 'M', 'ن'), (0x1EE2E, 'M', 'س'), (0x1EE2F, 'M', 'ع'), (0x1EE30, 'M', 'ف'), (0x1EE31, 'M', 'ص'), (0x1EE32, 'M', 'ق'), (0x1EE33, 'X'), ] def _seg_72() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1EE34, 'M', 'ش'), (0x1EE35, 'M', 'ت'), (0x1EE36, 'M', 'ث'), (0x1EE37, 'M', 'خ'), (0x1EE38, 'X'), (0x1EE39, 'M', 'ض'), (0x1EE3A, 'X'), (0x1EE3B, 'M', 'غ'), (0x1EE3C, 'X'), (0x1EE42, 'M', 'ج'), (0x1EE43, 'X'), (0x1EE47, 'M', 'ح'), (0x1EE48, 'X'), (0x1EE49, 'M', 'ي'), (0x1EE4A, 'X'), (0x1EE4B, 'M', 'ل'), (0x1EE4C, 'X'), (0x1EE4D, 'M', 'ن'), (0x1EE4E, 'M', 'س'), (0x1EE4F, 'M', 'ع'), (0x1EE50, 'X'), (0x1EE51, 'M', 'ص'), (0x1EE52, 'M', 'ق'), (0x1EE53, 'X'), (0x1EE54, 'M', 'ش'), (0x1EE55, 'X'), (0x1EE57, 'M', 'خ'), (0x1EE58, 'X'), (0x1EE59, 'M', 'ض'), (0x1EE5A, 'X'), (0x1EE5B, 'M', 'غ'), (0x1EE5C, 'X'), (0x1EE5D, 'M', 'ں'), (0x1EE5E, 'X'), (0x1EE5F, 'M', 'ٯ'), (0x1EE60, 'X'), (0x1EE61, 'M', 'ب'), (0x1EE62, 'M', 'ج'), (0x1EE63, 'X'), (0x1EE64, 'M', 'ه'), (0x1EE65, 'X'), (0x1EE67, 'M', 'ح'), (0x1EE68, 'M', 'ط'), (0x1EE69, 'M', 'ي'), (0x1EE6A, 'M', 'ك'), (0x1EE6B, 'X'), (0x1EE6C, 'M', 'م'), (0x1EE6D, 'M', 'ن'), (0x1EE6E, 'M', 'س'), (0x1EE6F, 'M', 'ع'), (0x1EE70, 'M', 'ف'), (0x1EE71, 'M', 'ص'), (0x1EE72, 'M', 'ق'), (0x1EE73, 'X'), (0x1EE74, 'M', 'ش'), (0x1EE75, 'M', 'ت'), (0x1EE76, 'M', 'ث'), (0x1EE77, 'M', 'خ'), (0x1EE78, 'X'), (0x1EE79, 'M', 'ض'), (0x1EE7A, 'M', 'ظ'), (0x1EE7B, 'M', 'غ'), (0x1EE7C, 'M', 'ٮ'), (0x1EE7D, 'X'), (0x1EE7E, 'M', 'ڡ'), (0x1EE7F, 'X'), (0x1EE80, 'M', 'ا'), (0x1EE81, 'M', 'ب'), (0x1EE82, 'M', 'ج'), (0x1EE83, 'M', 'د'), (0x1EE84, 'M', 'ه'), (0x1EE85, 'M', 'و'), (0x1EE86, 'M', 'ز'), (0x1EE87, 'M', 'ح'), (0x1EE88, 'M', 'ط'), (0x1EE89, 'M', 'ي'), (0x1EE8A, 'X'), (0x1EE8B, 'M', 'ل'), (0x1EE8C, 'M', 'م'), (0x1EE8D, 'M', 'ن'), (0x1EE8E, 'M', 'س'), (0x1EE8F, 'M', 'ع'), (0x1EE90, 'M', 'ف'), (0x1EE91, 'M', 'ص'), (0x1EE92, 'M', 'ق'), (0x1EE93, 'M', 'ر'), (0x1EE94, 'M', 'ش'), (0x1EE95, 'M', 'ت'), (0x1EE96, 'M', 'ث'), (0x1EE97, 'M', 'خ'), (0x1EE98, 'M', 'ذ'), (0x1EE99, 'M', 'ض'), (0x1EE9A, 'M', 'ظ'), (0x1EE9B, 'M', 'غ'), (0x1EE9C, 'X'), (0x1EEA1, 'M', 'ب'), (0x1EEA2, 'M', 'ج'), (0x1EEA3, 'M', 'د'), (0x1EEA4, 'X'), (0x1EEA5, 'M', 'و'), ] def _seg_73() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1EEA6, 'M', 'ز'), (0x1EEA7, 'M', 'ح'), (0x1EEA8, 'M', 'ط'), (0x1EEA9, 'M', 'ي'), (0x1EEAA, 'X'), (0x1EEAB, 'M', 'ل'), (0x1EEAC, 'M', 'م'), (0x1EEAD, 'M', 'ن'), (0x1EEAE, 'M', 'س'), (0x1EEAF, 'M', 'ع'), (0x1EEB0, 'M', 'ف'), (0x1EEB1, 'M', 'ص'), (0x1EEB2, 'M', 'ق'), (0x1EEB3, 'M', 'ر'), (0x1EEB4, 'M', 'ش'), (0x1EEB5, 'M', 'ت'), (0x1EEB6, 'M', 'ث'), (0x1EEB7, 'M', 'خ'), (0x1EEB8, 'M', 'ذ'), (0x1EEB9, 'M', 'ض'), (0x1EEBA, 'M', 'ظ'), (0x1EEBB, 'M', 'غ'), (0x1EEBC, 'X'), (0x1EEF0, 'V'), (0x1EEF2, 'X'), (0x1F000, 'V'), (0x1F02C, 'X'), (0x1F030, 'V'), (0x1F094, 'X'), (0x1F0A0, 'V'), (0x1F0AF, 'X'), (0x1F0B1, 'V'), (0x1F0C0, 'X'), (0x1F0C1, 'V'), (0x1F0D0, 'X'), (0x1F0D1, 'V'), (0x1F0F6, 'X'), (0x1F101, '3', '0,'), (0x1F102, '3', '1,'), (0x1F103, '3', '2,'), (0x1F104, '3', '3,'), (0x1F105, '3', '4,'), (0x1F106, '3', '5,'), (0x1F107, '3', '6,'), (0x1F108, '3', '7,'), (0x1F109, '3', '8,'), (0x1F10A, '3', '9,'), (0x1F10B, 'V'), (0x1F110, '3', '(a)'), (0x1F111, '3', '(b)'), (0x1F112, '3', '(c)'), (0x1F113, '3', '(d)'), (0x1F114, '3', '(e)'), (0x1F115, '3', '(f)'), (0x1F116, '3', '(g)'), (0x1F117, '3', '(h)'), (0x1F118, '3', '(i)'), (0x1F119, '3', '(j)'), (0x1F11A, '3', '(k)'), (0x1F11B, '3', '(l)'), (0x1F11C, '3', '(m)'), (0x1F11D, '3', '(n)'), (0x1F11E, '3', '(o)'), (0x1F11F, '3', '(p)'), (0x1F120, '3', '(q)'), (0x1F121, '3', '(r)'), (0x1F122, '3', '(s)'), (0x1F123, '3', '(t)'), (0x1F124, '3', '(u)'), (0x1F125, '3', '(v)'), (0x1F126, '3', '(w)'), (0x1F127, '3', '(x)'), (0x1F128, '3', '(y)'), (0x1F129, '3', '(z)'), (0x1F12A, 'M', '〔s〕'), (0x1F12B, 'M', 'c'), (0x1F12C, 'M', 'r'), (0x1F12D, 'M', 'cd'), (0x1F12E, 'M', 'wz'), (0x1F12F, 'V'), (0x1F130, 'M', 'a'), (0x1F131, 'M', 'b'), (0x1F132, 'M', 'c'), (0x1F133, 'M', 'd'), (0x1F134, 'M', 'e'), (0x1F135, 'M', 'f'), (0x1F136, 'M', 'g'), (0x1F137, 'M', 'h'), (0x1F138, 'M', 'i'), (0x1F139, 'M', 'j'), (0x1F13A, 'M', 'k'), (0x1F13B, 'M', 'l'), (0x1F13C, 'M', 'm'), (0x1F13D, 'M', 'n'), (0x1F13E, 'M', 'o'), (0x1F13F, 'M', 'p'), (0x1F140, 'M', 'q'), (0x1F141, 'M', 'r'), (0x1F142, 'M', 's'), (0x1F143, 'M', 't'), ] def _seg_74() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1F144, 'M', 'u'), (0x1F145, 'M', 'v'), (0x1F146, 'M', 'w'), (0x1F147, 'M', 'x'), (0x1F148, 'M', 'y'), (0x1F149, 'M', 'z'), (0x1F14A, 'M', 'hv'), (0x1F14B, 'M', 'mv'), (0x1F14C, 'M', 'sd'), (0x1F14D, 'M', 'ss'), (0x1F14E, 'M', 'ppv'), (0x1F14F, 'M', 'wc'), (0x1F150, 'V'), (0x1F16A, 'M', 'mc'), (0x1F16B, 'M', 'md'), (0x1F16C, 'M', 'mr'), (0x1F16D, 'V'), (0x1F190, 'M', 'dj'), (0x1F191, 'V'), (0x1F1AE, 'X'), (0x1F1E6, 'V'), (0x1F200, 'M', 'ほか'), (0x1F201, 'M', 'ココ'), (0x1F202, 'M', 'サ'), (0x1F203, 'X'), (0x1F210, 'M', '手'), (0x1F211, 'M', '字'), (0x1F212, 'M', '双'), (0x1F213, 'M', 'デ'), (0x1F214, 'M', '二'), (0x1F215, 'M', '多'), (0x1F216, 'M', '解'), (0x1F217, 'M', '天'), (0x1F218, 'M', '交'), (0x1F219, 'M', '映'), (0x1F21A, 'M', '無'), (0x1F21B, 'M', '料'), (0x1F21C, 'M', '前'), (0x1F21D, 'M', '後'), (0x1F21E, 'M', '再'), (0x1F21F, 'M', '新'), (0x1F220, 'M', '初'), (0x1F221, 'M', '終'), (0x1F222, 'M', '生'), (0x1F223, 'M', '販'), (0x1F224, 'M', '声'), (0x1F225, 'M', '吹'), (0x1F226, 'M', '演'), (0x1F227, 'M', '投'), (0x1F228, 'M', '捕'), (0x1F229, 'M', '一'), (0x1F22A, 'M', '三'), (0x1F22B, 'M', '遊'), (0x1F22C, 'M', '左'), (0x1F22D, 'M', '中'), (0x1F22E, 'M', '右'), (0x1F22F, 'M', '指'), (0x1F230, 'M', '走'), (0x1F231, 'M', '打'), (0x1F232, 'M', '禁'), (0x1F233, 'M', '空'), (0x1F234, 'M', '合'), (0x1F235, 'M', '満'), (0x1F236, 'M', '有'), (0x1F237, 'M', '月'), (0x1F238, 'M', '申'), (0x1F239, 'M', '割'), (0x1F23A, 'M', '営'), (0x1F23B, 'M', '配'), (0x1F23C, 'X'), (0x1F240, 'M', '〔本〕'), (0x1F241, 'M', '〔三〕'), (0x1F242, 'M', '〔二〕'), (0x1F243, 'M', '〔安〕'), (0x1F244, 'M', '〔点〕'), (0x1F245, 'M', '〔打〕'), (0x1F246, 'M', '〔盗〕'), (0x1F247, 'M', '〔勝〕'), (0x1F248, 'M', '〔敗〕'), (0x1F249, 'X'), (0x1F250, 'M', '得'), (0x1F251, 'M', '可'), (0x1F252, 'X'), (0x1F260, 'V'), (0x1F266, 'X'), (0x1F300, 'V'), (0x1F6D8, 'X'), (0x1F6DD, 'V'), (0x1F6ED, 'X'), (0x1F6F0, 'V'), (0x1F6FD, 'X'), (0x1F700, 'V'), (0x1F774, 'X'), (0x1F780, 'V'), (0x1F7D9, 'X'), (0x1F7E0, 'V'), (0x1F7EC, 'X'), (0x1F7F0, 'V'), (0x1F7F1, 'X'), (0x1F800, 'V'), ] def _seg_75() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1F80C, 'X'), (0x1F810, 'V'), (0x1F848, 'X'), (0x1F850, 'V'), (0x1F85A, 'X'), (0x1F860, 'V'), (0x1F888, 'X'), (0x1F890, 'V'), (0x1F8AE, 'X'), (0x1F8B0, 'V'), (0x1F8B2, 'X'), (0x1F900, 'V'), (0x1FA54, 'X'), (0x1FA60, 'V'), (0x1FA6E, 'X'), (0x1FA70, 'V'), (0x1FA75, 'X'), (0x1FA78, 'V'), (0x1FA7D, 'X'), (0x1FA80, 'V'), (0x1FA87, 'X'), (0x1FA90, 'V'), (0x1FAAD, 'X'), (0x1FAB0, 'V'), (0x1FABB, 'X'), (0x1FAC0, 'V'), (0x1FAC6, 'X'), (0x1FAD0, 'V'), (0x1FADA, 'X'), (0x1FAE0, 'V'), (0x1FAE8, 'X'), (0x1FAF0, 'V'), (0x1FAF7, 'X'), (0x1FB00, 'V'), (0x1FB93, 'X'), (0x1FB94, 'V'), (0x1FBCB, 'X'), (0x1FBF0, 'M', '0'), (0x1FBF1, 'M', '1'), (0x1FBF2, 'M', '2'), (0x1FBF3, 'M', '3'), (0x1FBF4, 'M', '4'), (0x1FBF5, 'M', '5'), (0x1FBF6, 'M', '6'), (0x1FBF7, 'M', '7'), (0x1FBF8, 'M', '8'), (0x1FBF9, 'M', '9'), (0x1FBFA, 'X'), (0x20000, 'V'), (0x2A6E0, 'X'), (0x2A700, 'V'), (0x2B739, 'X'), (0x2B740, 'V'), (0x2B81E, 'X'), (0x2B820, 'V'), (0x2CEA2, 'X'), (0x2CEB0, 'V'), (0x2EBE1, 'X'), (0x2F800, 'M', '丽'), (0x2F801, 'M', '丸'), (0x2F802, 'M', '乁'), (0x2F803, 'M', '𠄢'), (0x2F804, 'M', '你'), (0x2F805, 'M', '侮'), (0x2F806, 'M', '侻'), (0x2F807, 'M', '倂'), (0x2F808, 'M', '偺'), (0x2F809, 'M', '備'), (0x2F80A, 'M', '僧'), (0x2F80B, 'M', '像'), (0x2F80C, 'M', '㒞'), (0x2F80D, 'M', '𠘺'), (0x2F80E, 'M', '免'), (0x2F80F, 'M', '兔'), (0x2F810, 'M', '兤'), (0x2F811, 'M', '具'), (0x2F812, 'M', '𠔜'), (0x2F813, 'M', '㒹'), (0x2F814, 'M', '內'), (0x2F815, 'M', '再'), (0x2F816, 'M', '𠕋'), (0x2F817, 'M', '冗'), (0x2F818, 'M', '冤'), (0x2F819, 'M', '仌'), (0x2F81A, 'M', '冬'), (0x2F81B, 'M', '况'), (0x2F81C, 'M', '𩇟'), (0x2F81D, 'M', '凵'), (0x2F81E, 'M', '刃'), (0x2F81F, 'M', '㓟'), (0x2F820, 'M', '刻'), (0x2F821, 'M', '剆'), (0x2F822, 'M', '割'), (0x2F823, 'M', '剷'), (0x2F824, 'M', '㔕'), (0x2F825, 'M', '勇'), (0x2F826, 'M', '勉'), (0x2F827, 'M', '勤'), (0x2F828, 'M', '勺'), (0x2F829, 'M', '包'), ] def _seg_76() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F82A, 'M', '匆'), (0x2F82B, 'M', '北'), (0x2F82C, 'M', '卉'), (0x2F82D, 'M', '卑'), (0x2F82E, 'M', '博'), (0x2F82F, 'M', '即'), (0x2F830, 'M', '卽'), (0x2F831, 'M', '卿'), (0x2F834, 'M', '𠨬'), (0x2F835, 'M', '灰'), (0x2F836, 'M', '及'), (0x2F837, 'M', '叟'), (0x2F838, 'M', '𠭣'), (0x2F839, 'M', '叫'), (0x2F83A, 'M', '叱'), (0x2F83B, 'M', '吆'), (0x2F83C, 'M', '咞'), (0x2F83D, 'M', '吸'), (0x2F83E, 'M', '呈'), (0x2F83F, 'M', '周'), (0x2F840, 'M', '咢'), (0x2F841, 'M', '哶'), (0x2F842, 'M', '唐'), (0x2F843, 'M', '啓'), (0x2F844, 'M', '啣'), (0x2F845, 'M', '善'), (0x2F847, 'M', '喙'), (0x2F848, 'M', '喫'), (0x2F849, 'M', '喳'), (0x2F84A, 'M', '嗂'), (0x2F84B, 'M', '圖'), (0x2F84C, 'M', '嘆'), (0x2F84D, 'M', '圗'), (0x2F84E, 'M', '噑'), (0x2F84F, 'M', '噴'), (0x2F850, 'M', '切'), (0x2F851, 'M', '壮'), (0x2F852, 'M', '城'), (0x2F853, 'M', '埴'), (0x2F854, 'M', '堍'), (0x2F855, 'M', '型'), (0x2F856, 'M', '堲'), (0x2F857, 'M', '報'), (0x2F858, 'M', '墬'), (0x2F859, 'M', '𡓤'), (0x2F85A, 'M', '売'), (0x2F85B, 'M', '壷'), (0x2F85C, 'M', '夆'), (0x2F85D, 'M', '多'), (0x2F85E, 'M', '夢'), (0x2F85F, 'M', '奢'), (0x2F860, 'M', '𡚨'), (0x2F861, 'M', '𡛪'), (0x2F862, 'M', '姬'), (0x2F863, 'M', '娛'), (0x2F864, 'M', '娧'), (0x2F865, 'M', '姘'), (0x2F866, 'M', '婦'), (0x2F867, 'M', '㛮'), (0x2F868, 'X'), (0x2F869, 'M', '嬈'), (0x2F86A, 'M', '嬾'), (0x2F86C, 'M', '𡧈'), (0x2F86D, 'M', '寃'), (0x2F86E, 'M', '寘'), (0x2F86F, 'M', '寧'), (0x2F870, 'M', '寳'), (0x2F871, 'M', '𡬘'), (0x2F872, 'M', '寿'), (0x2F873, 'M', '将'), (0x2F874, 'X'), (0x2F875, 'M', '尢'), (0x2F876, 'M', '㞁'), (0x2F877, 'M', '屠'), (0x2F878, 'M', '屮'), (0x2F879, 'M', '峀'), (0x2F87A, 'M', '岍'), (0x2F87B, 'M', '𡷤'), (0x2F87C, 'M', '嵃'), (0x2F87D, 'M', '𡷦'), (0x2F87E, 'M', '嵮'), (0x2F87F, 'M', '嵫'), (0x2F880, 'M', '嵼'), (0x2F881, 'M', '巡'), (0x2F882, 'M', '巢'), (0x2F883, 'M', '㠯'), (0x2F884, 'M', '巽'), (0x2F885, 'M', '帨'), (0x2F886, 'M', '帽'), (0x2F887, 'M', '幩'), (0x2F888, 'M', '㡢'), (0x2F889, 'M', '𢆃'), (0x2F88A, 'M', '㡼'), (0x2F88B, 'M', '庰'), (0x2F88C, 'M', '庳'), (0x2F88D, 'M', '庶'), (0x2F88E, 'M', '廊'), (0x2F88F, 'M', '𪎒'), (0x2F890, 'M', '廾'), (0x2F891, 'M', '𢌱'), ] def _seg_77() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F893, 'M', '舁'), (0x2F894, 'M', '弢'), (0x2F896, 'M', '㣇'), (0x2F897, 'M', '𣊸'), (0x2F898, 'M', '𦇚'), (0x2F899, 'M', '形'), (0x2F89A, 'M', '彫'), (0x2F89B, 'M', '㣣'), (0x2F89C, 'M', '徚'), (0x2F89D, 'M', '忍'), (0x2F89E, 'M', '志'), (0x2F89F, 'M', '忹'), (0x2F8A0, 'M', '悁'), (0x2F8A1, 'M', '㤺'), (0x2F8A2, 'M', '㤜'), (0x2F8A3, 'M', '悔'), (0x2F8A4, 'M', '𢛔'), (0x2F8A5, 'M', '惇'), (0x2F8A6, 'M', '慈'), (0x2F8A7, 'M', '慌'), (0x2F8A8, 'M', '慎'), (0x2F8A9, 'M', '慌'), (0x2F8AA, 'M', '慺'), (0x2F8AB, 'M', '憎'), (0x2F8AC, 'M', '憲'), (0x2F8AD, 'M', '憤'), (0x2F8AE, 'M', '憯'), (0x2F8AF, 'M', '懞'), (0x2F8B0, 'M', '懲'), (0x2F8B1, 'M', '懶'), (0x2F8B2, 'M', '成'), (0x2F8B3, 'M', '戛'), (0x2F8B4, 'M', '扝'), (0x2F8B5, 'M', '抱'), (0x2F8B6, 'M', '拔'), (0x2F8B7, 'M', '捐'), (0x2F8B8, 'M', '𢬌'), (0x2F8B9, 'M', '挽'), (0x2F8BA, 'M', '拼'), (0x2F8BB, 'M', '捨'), (0x2F8BC, 'M', '掃'), (0x2F8BD, 'M', '揤'), (0x2F8BE, 'M', '𢯱'), (0x2F8BF, 'M', '搢'), (0x2F8C0, 'M', '揅'), (0x2F8C1, 'M', '掩'), (0x2F8C2, 'M', '㨮'), (0x2F8C3, 'M', '摩'), (0x2F8C4, 'M', '摾'), (0x2F8C5, 'M', '撝'), (0x2F8C6, 'M', '摷'), (0x2F8C7, 'M', '㩬'), (0x2F8C8, 'M', '敏'), (0x2F8C9, 'M', '敬'), (0x2F8CA, 'M', '𣀊'), (0x2F8CB, 'M', '旣'), (0x2F8CC, 'M', '書'), (0x2F8CD, 'M', '晉'), (0x2F8CE, 'M', '㬙'), (0x2F8CF, 'M', '暑'), (0x2F8D0, 'M', '㬈'), (0x2F8D1, 'M', '㫤'), (0x2F8D2, 'M', '冒'), (0x2F8D3, 'M', '冕'), (0x2F8D4, 'M', '最'), (0x2F8D5, 'M', '暜'), (0x2F8D6, 'M', '肭'), (0x2F8D7, 'M', '䏙'), (0x2F8D8, 'M', '朗'), (0x2F8D9, 'M', '望'), (0x2F8DA, 'M', '朡'), (0x2F8DB, 'M', '杞'), (0x2F8DC, 'M', '杓'), (0x2F8DD, 'M', '𣏃'), (0x2F8DE, 'M', '㭉'), (0x2F8DF, 'M', '柺'), (0x2F8E0, 'M', '枅'), (0x2F8E1, 'M', '桒'), (0x2F8E2, 'M', '梅'), (0x2F8E3, 'M', '𣑭'), (0x2F8E4, 'M', '梎'), (0x2F8E5, 'M', '栟'), (0x2F8E6, 'M', '椔'), (0x2F8E7, 'M', '㮝'), (0x2F8E8, 'M', '楂'), (0x2F8E9, 'M', '榣'), (0x2F8EA, 'M', '槪'), (0x2F8EB, 'M', '檨'), (0x2F8EC, 'M', '𣚣'), (0x2F8ED, 'M', '櫛'), (0x2F8EE, 'M', '㰘'), (0x2F8EF, 'M', '次'), (0x2F8F0, 'M', '𣢧'), (0x2F8F1, 'M', '歔'), (0x2F8F2, 'M', '㱎'), (0x2F8F3, 'M', '歲'), (0x2F8F4, 'M', '殟'), (0x2F8F5, 'M', '殺'), (0x2F8F6, 'M', '殻'), (0x2F8F7, 'M', '𣪍'), ] def _seg_78() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F8F8, 'M', '𡴋'), (0x2F8F9, 'M', '𣫺'), (0x2F8FA, 'M', '汎'), (0x2F8FB, 'M', '𣲼'), (0x2F8FC, 'M', '沿'), (0x2F8FD, 'M', '泍'), (0x2F8FE, 'M', '汧'), (0x2F8FF, 'M', '洖'), (0x2F900, 'M', '派'), (0x2F901, 'M', '海'), (0x2F902, 'M', '流'), (0x2F903, 'M', '浩'), (0x2F904, 'M', '浸'), (0x2F905, 'M', '涅'), (0x2F906, 'M', '𣴞'), (0x2F907, 'M', '洴'), (0x2F908, 'M', '港'), (0x2F909, 'M', '湮'), (0x2F90A, 'M', '㴳'), (0x2F90B, 'M', '滋'), (0x2F90C, 'M', '滇'), (0x2F90D, 'M', '𣻑'), (0x2F90E, 'M', '淹'), (0x2F90F, 'M', '潮'), (0x2F910, 'M', '𣽞'), (0x2F911, 'M', '𣾎'), (0x2F912, 'M', '濆'), (0x2F913, 'M', '瀹'), (0x2F914, 'M', '瀞'), (0x2F915, 'M', '瀛'), (0x2F916, 'M', '㶖'), (0x2F917, 'M', '灊'), (0x2F918, 'M', '災'), (0x2F919, 'M', '灷'), (0x2F91A, 'M', '炭'), (0x2F91B, 'M', '𠔥'), (0x2F91C, 'M', '煅'), (0x2F91D, 'M', '𤉣'), (0x2F91E, 'M', '熜'), (0x2F91F, 'X'), (0x2F920, 'M', '爨'), (0x2F921, 'M', '爵'), (0x2F922, 'M', '牐'), (0x2F923, 'M', '𤘈'), (0x2F924, 'M', '犀'), (0x2F925, 'M', '犕'), (0x2F926, 'M', '𤜵'), (0x2F927, 'M', '𤠔'), (0x2F928, 'M', '獺'), (0x2F929, 'M', '王'), (0x2F92A, 'M', '㺬'), (0x2F92B, 'M', '玥'), (0x2F92C, 'M', '㺸'), (0x2F92E, 'M', '瑇'), (0x2F92F, 'M', '瑜'), (0x2F930, 'M', '瑱'), (0x2F931, 'M', '璅'), (0x2F932, 'M', '瓊'), (0x2F933, 'M', '㼛'), (0x2F934, 'M', '甤'), (0x2F935, 'M', '𤰶'), (0x2F936, 'M', '甾'), (0x2F937, 'M', '𤲒'), (0x2F938, 'M', '異'), (0x2F939, 'M', '𢆟'), (0x2F93A, 'M', '瘐'), (0x2F93B, 'M', '𤾡'), (0x2F93C, 'M', '𤾸'), (0x2F93D, 'M', '𥁄'), (0x2F93E, 'M', '㿼'), (0x2F93F, 'M', '䀈'), (0x2F940, 'M', '直'), (0x2F941, 'M', '𥃳'), (0x2F942, 'M', '𥃲'), (0x2F943, 'M', '𥄙'), (0x2F944, 'M', '𥄳'), (0x2F945, 'M', '眞'), (0x2F946, 'M', '真'), (0x2F948, 'M', '睊'), (0x2F949, 'M', '䀹'), (0x2F94A, 'M', '瞋'), (0x2F94B, 'M', '䁆'), (0x2F94C, 'M', '䂖'), (0x2F94D, 'M', '𥐝'), (0x2F94E, 'M', '硎'), (0x2F94F, 'M', '碌'), (0x2F950, 'M', '磌'), (0x2F951, 'M', '䃣'), (0x2F952, 'M', '𥘦'), (0x2F953, 'M', '祖'), (0x2F954, 'M', '𥚚'), (0x2F955, 'M', '𥛅'), (0x2F956, 'M', '福'), (0x2F957, 'M', '秫'), (0x2F958, 'M', '䄯'), (0x2F959, 'M', '穀'), (0x2F95A, 'M', '穊'), (0x2F95B, 'M', '穏'), (0x2F95C, 'M', '𥥼'), (0x2F95D, 'M', '𥪧'), ] def _seg_79() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F95F, 'X'), (0x2F960, 'M', '䈂'), (0x2F961, 'M', '𥮫'), (0x2F962, 'M', '篆'), (0x2F963, 'M', '築'), (0x2F964, 'M', '䈧'), (0x2F965, 'M', '𥲀'), (0x2F966, 'M', '糒'), (0x2F967, 'M', '䊠'), (0x2F968, 'M', '糨'), (0x2F969, 'M', '糣'), (0x2F96A, 'M', '紀'), (0x2F96B, 'M', '𥾆'), (0x2F96C, 'M', '絣'), (0x2F96D, 'M', '䌁'), (0x2F96E, 'M', '緇'), (0x2F96F, 'M', '縂'), (0x2F970, 'M', '繅'), (0x2F971, 'M', '䌴'), (0x2F972, 'M', '𦈨'), (0x2F973, 'M', '𦉇'), (0x2F974, 'M', '䍙'), (0x2F975, 'M', '𦋙'), (0x2F976, 'M', '罺'), (0x2F977, 'M', '𦌾'), (0x2F978, 'M', '羕'), (0x2F979, 'M', '翺'), (0x2F97A, 'M', '者'), (0x2F97B, 'M', '𦓚'), (0x2F97C, 'M', '𦔣'), (0x2F97D, 'M', '聠'), (0x2F97E, 'M', '𦖨'), (0x2F97F, 'M', '聰'), (0x2F980, 'M', '𣍟'), (0x2F981, 'M', '䏕'), (0x2F982, 'M', '育'), (0x2F983, 'M', '脃'), (0x2F984, 'M', '䐋'), (0x2F985, 'M', '脾'), (0x2F986, 'M', '媵'), (0x2F987, 'M', '𦞧'), (0x2F988, 'M', '𦞵'), (0x2F989, 'M', '𣎓'), (0x2F98A, 'M', '𣎜'), (0x2F98B, 'M', '舁'), (0x2F98C, 'M', '舄'), (0x2F98D, 'M', '辞'), (0x2F98E, 'M', '䑫'), (0x2F98F, 'M', '芑'), (0x2F990, 'M', '芋'), (0x2F991, 'M', '芝'), (0x2F992, 'M', '劳'), (0x2F993, 'M', '花'), (0x2F994, 'M', '芳'), (0x2F995, 'M', '芽'), (0x2F996, 'M', '苦'), (0x2F997, 'M', '𦬼'), (0x2F998, 'M', '若'), (0x2F999, 'M', '茝'), (0x2F99A, 'M', '荣'), (0x2F99B, 'M', '莭'), (0x2F99C, 'M', '茣'), (0x2F99D, 'M', '莽'), (0x2F99E, 'M', '菧'), (0x2F99F, 'M', '著'), (0x2F9A0, 'M', '荓'), (0x2F9A1, 'M', '菊'), (0x2F9A2, 'M', '菌'), (0x2F9A3, 'M', '菜'), (0x2F9A4, 'M', '𦰶'), (0x2F9A5, 'M', '𦵫'), (0x2F9A6, 'M', '𦳕'), (0x2F9A7, 'M', '䔫'), (0x2F9A8, 'M', '蓱'), (0x2F9A9, 'M', '蓳'), (0x2F9AA, 'M', '蔖'), (0x2F9AB, 'M', '𧏊'), (0x2F9AC, 'M', '蕤'), (0x2F9AD, 'M', '𦼬'), (0x2F9AE, 'M', '䕝'), (0x2F9AF, 'M', '䕡'), (0x2F9B0, 'M', '𦾱'), (0x2F9B1, 'M', '𧃒'), (0x2F9B2, 'M', '䕫'), (0x2F9B3, 'M', '虐'), (0x2F9B4, 'M', '虜'), (0x2F9B5, 'M', '虧'), (0x2F9B6, 'M', '虩'), (0x2F9B7, 'M', '蚩'), (0x2F9B8, 'M', '蚈'), (0x2F9B9, 'M', '蜎'), (0x2F9BA, 'M', '蛢'), (0x2F9BB, 'M', '蝹'), (0x2F9BC, 'M', '蜨'), (0x2F9BD, 'M', '蝫'), (0x2F9BE, 'M', '螆'), (0x2F9BF, 'X'), (0x2F9C0, 'M', '蟡'), (0x2F9C1, 'M', '蠁'), (0x2F9C2, 'M', '䗹'), ] def _seg_80() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F9C3, 'M', '衠'), (0x2F9C4, 'M', '衣'), (0x2F9C5, 'M', '𧙧'), (0x2F9C6, 'M', '裗'), (0x2F9C7, 'M', '裞'), (0x2F9C8, 'M', '䘵'), (0x2F9C9, 'M', '裺'), (0x2F9CA, 'M', '㒻'), (0x2F9CB, 'M', '𧢮'), (0x2F9CC, 'M', '𧥦'), (0x2F9CD, 'M', '䚾'), (0x2F9CE, 'M', '䛇'), (0x2F9CF, 'M', '誠'), (0x2F9D0, 'M', '諭'), (0x2F9D1, 'M', '變'), (0x2F9D2, 'M', '豕'), (0x2F9D3, 'M', '𧲨'), (0x2F9D4, 'M', '貫'), (0x2F9D5, 'M', '賁'), (0x2F9D6, 'M', '贛'), (0x2F9D7, 'M', '起'), (0x2F9D8, 'M', '𧼯'), (0x2F9D9, 'M', '𠠄'), (0x2F9DA, 'M', '跋'), (0x2F9DB, 'M', '趼'), (0x2F9DC, 'M', '跰'), (0x2F9DD, 'M', '𠣞'), (0x2F9DE, 'M', '軔'), (0x2F9DF, 'M', '輸'), (0x2F9E0, 'M', '𨗒'), (0x2F9E1, 'M', '𨗭'), (0x2F9E2, 'M', '邔'), (0x2F9E3, 'M', '郱'), (0x2F9E4, 'M', '鄑'), (0x2F9E5, 'M', '𨜮'), (0x2F9E6, 'M', '鄛'), (0x2F9E7, 'M', '鈸'), (0x2F9E8, 'M', '鋗'), (0x2F9E9, 'M', '鋘'), (0x2F9EA, 'M', '鉼'), (0x2F9EB, 'M', '鏹'), (0x2F9EC, 'M', '鐕'), (0x2F9ED, 'M', '𨯺'), (0x2F9EE, 'M', '開'), (0x2F9EF, 'M', '䦕'), (0x2F9F0, 'M', '閷'), (0x2F9F1, 'M', '𨵷'), (0x2F9F2, 'M', '䧦'), (0x2F9F3, 'M', '雃'), (0x2F9F4, 'M', '嶲'), (0x2F9F5, 'M', '霣'), (0x2F9F6, 'M', '𩅅'), (0x2F9F7, 'M', '𩈚'), (0x2F9F8, 'M', '䩮'), (0x2F9F9, 'M', '䩶'), (0x2F9FA, 'M', '韠'), (0x2F9FB, 'M', '𩐊'), (0x2F9FC, 'M', '䪲'), (0x2F9FD, 'M', '𩒖'), (0x2F9FE, 'M', '頋'), (0x2FA00, 'M', '頩'), (0x2FA01, 'M', '𩖶'), (0x2FA02, 'M', '飢'), (0x2FA03, 'M', '䬳'), (0x2FA04, 'M', '餩'), (0x2FA05, 'M', '馧'), (0x2FA06, 'M', '駂'), (0x2FA07, 'M', '駾'), (0x2FA08, 'M', '䯎'), (0x2FA09, 'M', '𩬰'), (0x2FA0A, 'M', '鬒'), (0x2FA0B, 'M', '鱀'), (0x2FA0C, 'M', '鳽'), (0x2FA0D, 'M', '䳎'), (0x2FA0E, 'M', '䳭'), (0x2FA0F, 'M', '鵧'), (0x2FA10, 'M', '𪃎'), (0x2FA11, 'M', '䳸'), (0x2FA12, 'M', '𪄅'), (0x2FA13, 'M', '𪈎'), (0x2FA14, 'M', '𪊑'), (0x2FA15, 'M', '麻'), (0x2FA16, 'M', '䵖'), (0x2FA17, 'M', '黹'), (0x2FA18, 'M', '黾'), (0x2FA19, 'M', '鼅'), (0x2FA1A, 'M', '鼏'), (0x2FA1B, 'M', '鼖'), (0x2FA1C, 'M', '鼻'), (0x2FA1D, 'M', '𪘀'), (0x2FA1E, 'X'), (0x30000, 'V'), (0x3134B, 'X'), (0xE0100, 'I'), (0xE01F0, 'X'), ] uts46data = tuple( _seg_0() + _seg_1() + _seg_2() + _seg_3() + _seg_4() + _seg_5() + _seg_6() + _seg_7() + _seg_8() + _seg_9() + _seg_10() + _seg_11() + _seg_12() + _seg_13() + _seg_14() + _seg_15() + _seg_16() + _seg_17() + _seg_18() + _seg_19() + _seg_20() + _seg_21() + _seg_22() + _seg_23() + _seg_24() + _seg_25() + _seg_26() + _seg_27() + _seg_28() + _seg_29() + _seg_30() + _seg_31() + _seg_32() + _seg_33() + _seg_34() + _seg_35() + _seg_36() + _seg_37() + _seg_38() + _seg_39() + _seg_40() + _seg_41() + _seg_42() + _seg_43() + _seg_44() + _seg_45() + _seg_46() + _seg_47() + _seg_48() + _seg_49() + _seg_50() + _seg_51() + _seg_52() + _seg_53() + _seg_54() + _seg_55() + _seg_56() + _seg_57() + _seg_58() + _seg_59() + _seg_60() + _seg_61() + _seg_62() + _seg_63() + _seg_64() + _seg_65() + _seg_66() + _seg_67() + _seg_68() + _seg_69() + _seg_70() + _seg_71() + _seg_72() + _seg_73() + _seg_74() + _seg_75() + _seg_76() + _seg_77() + _seg_78() + _seg_79() + _seg_80() ) # type: Tuple[Union[Tuple[int, str], Tuple[int, str, str]], ...]
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/idna/uts46data.py
uts46data.py
from . import idnadata import bisect import unicodedata import re from typing import Union, Optional from .intranges import intranges_contain _virama_combining_class = 9 _alabel_prefix = b'xn--' _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]') class IDNAError(UnicodeError): """ Base exception for all IDNA-encoding related problems """ pass class IDNABidiError(IDNAError): """ Exception when bidirectional requirements are not satisfied """ pass class InvalidCodepoint(IDNAError): """ Exception when a disallowed or unallocated codepoint is used """ pass class InvalidCodepointContext(IDNAError): """ Exception when the codepoint is not valid in the context it is used """ pass def _combining_class(cp: int) -> int: v = unicodedata.combining(chr(cp)) if v == 0: if not unicodedata.name(chr(cp)): raise ValueError('Unknown character in unicodedata') return v def _is_script(cp: str, script: str) -> bool: return intranges_contain(ord(cp), idnadata.scripts[script]) def _punycode(s: str) -> bytes: return s.encode('punycode') def _unot(s: int) -> str: return 'U+{:04X}'.format(s) def valid_label_length(label: Union[bytes, str]) -> bool: if len(label) > 63: return False return True def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool: if len(label) > (254 if trailing_dot else 253): return False return True def check_bidi(label: str, check_ltr: bool = False) -> bool: # Bidi rules should only be applied if string contains RTL characters bidi_label = False for (idx, cp) in enumerate(label, 1): direction = unicodedata.bidirectional(cp) if direction == '': # String likely comes from a newer version of Unicode raise IDNABidiError('Unknown directionality in label {} at position {}'.format(repr(label), idx)) if direction in ['R', 'AL', 'AN']: bidi_label = True if not bidi_label and not check_ltr: return True # Bidi rule 1 direction = unicodedata.bidirectional(label[0]) if direction in ['R', 'AL']: rtl = True elif direction == 'L': rtl = False else: raise IDNABidiError('First codepoint in label {} must be directionality L, R or AL'.format(repr(label))) valid_ending = False number_type = None # type: Optional[str] for (idx, cp) in enumerate(label, 1): direction = unicodedata.bidirectional(cp) if rtl: # Bidi rule 2 if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: raise IDNABidiError('Invalid direction for codepoint at position {} in a right-to-left label'.format(idx)) # Bidi rule 3 if direction in ['R', 'AL', 'EN', 'AN']: valid_ending = True elif direction != 'NSM': valid_ending = False # Bidi rule 4 if direction in ['AN', 'EN']: if not number_type: number_type = direction else: if number_type != direction: raise IDNABidiError('Can not mix numeral types in a right-to-left label') else: # Bidi rule 5 if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: raise IDNABidiError('Invalid direction for codepoint at position {} in a left-to-right label'.format(idx)) # Bidi rule 6 if direction in ['L', 'EN']: valid_ending = True elif direction != 'NSM': valid_ending = False if not valid_ending: raise IDNABidiError('Label ends with illegal codepoint directionality') return True def check_initial_combiner(label: str) -> bool: if unicodedata.category(label[0])[0] == 'M': raise IDNAError('Label begins with an illegal combining character') return True def check_hyphen_ok(label: str) -> bool: if label[2:4] == '--': raise IDNAError('Label has disallowed hyphens in 3rd and 4th position') if label[0] == '-' or label[-1] == '-': raise IDNAError('Label must not start or end with a hyphen') return True def check_nfc(label: str) -> None: if unicodedata.normalize('NFC', label) != label: raise IDNAError('Label must be in Normalization Form C') def valid_contextj(label: str, pos: int) -> bool: cp_value = ord(label[pos]) if cp_value == 0x200c: if pos > 0: if _combining_class(ord(label[pos - 1])) == _virama_combining_class: return True ok = False for i in range(pos-1, -1, -1): joining_type = idnadata.joining_types.get(ord(label[i])) if joining_type == ord('T'): continue if joining_type in [ord('L'), ord('D')]: ok = True break if not ok: return False ok = False for i in range(pos+1, len(label)): joining_type = idnadata.joining_types.get(ord(label[i])) if joining_type == ord('T'): continue if joining_type in [ord('R'), ord('D')]: ok = True break return ok if cp_value == 0x200d: if pos > 0: if _combining_class(ord(label[pos - 1])) == _virama_combining_class: return True return False else: return False def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: cp_value = ord(label[pos]) if cp_value == 0x00b7: if 0 < pos < len(label)-1: if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c: return True return False elif cp_value == 0x0375: if pos < len(label)-1 and len(label) > 1: return _is_script(label[pos + 1], 'Greek') return False elif cp_value == 0x05f3 or cp_value == 0x05f4: if pos > 0: return _is_script(label[pos - 1], 'Hebrew') return False elif cp_value == 0x30fb: for cp in label: if cp == '\u30fb': continue if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'): return True return False elif 0x660 <= cp_value <= 0x669: for cp in label: if 0x6f0 <= ord(cp) <= 0x06f9: return False return True elif 0x6f0 <= cp_value <= 0x6f9: for cp in label: if 0x660 <= ord(cp) <= 0x0669: return False return True return False def check_label(label: Union[str, bytes, bytearray]) -> None: if isinstance(label, (bytes, bytearray)): label = label.decode('utf-8') if len(label) == 0: raise IDNAError('Empty Label') check_nfc(label) check_hyphen_ok(label) check_initial_combiner(label) for (pos, cp) in enumerate(label): cp_value = ord(cp) if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']): continue elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']): try: if not valid_contextj(label, pos): raise InvalidCodepointContext('Joiner {} not allowed at position {} in {}'.format( _unot(cp_value), pos+1, repr(label))) except ValueError: raise IDNAError('Unknown codepoint adjacent to joiner {} at position {} in {}'.format( _unot(cp_value), pos+1, repr(label))) elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']): if not valid_contexto(label, pos): raise InvalidCodepointContext('Codepoint {} not allowed at position {} in {}'.format(_unot(cp_value), pos+1, repr(label))) else: raise InvalidCodepoint('Codepoint {} at position {} of {} not allowed'.format(_unot(cp_value), pos+1, repr(label))) check_bidi(label) def alabel(label: str) -> bytes: try: label_bytes = label.encode('ascii') ulabel(label_bytes) if not valid_label_length(label_bytes): raise IDNAError('Label too long') return label_bytes except UnicodeEncodeError: pass if not label: raise IDNAError('No Input') label = str(label) check_label(label) label_bytes = _punycode(label) label_bytes = _alabel_prefix + label_bytes if not valid_label_length(label_bytes): raise IDNAError('Label too long') return label_bytes def ulabel(label: Union[str, bytes, bytearray]) -> str: if not isinstance(label, (bytes, bytearray)): try: label_bytes = label.encode('ascii') except UnicodeEncodeError: check_label(label) return label else: label_bytes = label label_bytes = label_bytes.lower() if label_bytes.startswith(_alabel_prefix): label_bytes = label_bytes[len(_alabel_prefix):] if not label_bytes: raise IDNAError('Malformed A-label, no Punycode eligible content found') if label_bytes.decode('ascii')[-1] == '-': raise IDNAError('A-label must not end with a hyphen') else: check_label(label_bytes) return label_bytes.decode('ascii') try: label = label_bytes.decode('punycode') except UnicodeError: raise IDNAError('Invalid A-label') check_label(label) return label def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: """Re-map the characters in the string according to UTS46 processing.""" from .uts46data import uts46data output = '' for pos, char in enumerate(domain): code_point = ord(char) try: uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, 'Z')) - 1] status = uts46row[1] replacement = None # type: Optional[str] if len(uts46row) == 3: replacement = uts46row[2] # type: ignore if (status == 'V' or (status == 'D' and not transitional) or (status == '3' and not std3_rules and replacement is None)): output += char elif replacement is not None and (status == 'M' or (status == '3' and not std3_rules) or (status == 'D' and transitional)): output += replacement elif status != 'I': raise IndexError() except IndexError: raise InvalidCodepoint( 'Codepoint {} not allowed at position {} in {}'.format( _unot(code_point), pos + 1, repr(domain))) return unicodedata.normalize('NFC', output) def encode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False, transitional: bool = False) -> bytes: if isinstance(s, (bytes, bytearray)): s = s.decode('ascii') if uts46: s = uts46_remap(s, std3_rules, transitional) trailing_dot = False result = [] if strict: labels = s.split('.') else: labels = _unicode_dots_re.split(s) if not labels or labels == ['']: raise IDNAError('Empty domain') if labels[-1] == '': del labels[-1] trailing_dot = True for label in labels: s = alabel(label) if s: result.append(s) else: raise IDNAError('Empty label') if trailing_dot: result.append(b'') s = b'.'.join(result) if not valid_string_length(s, trailing_dot): raise IDNAError('Domain too long') return s def decode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False) -> str: try: if isinstance(s, (bytes, bytearray)): s = s.decode('ascii') except UnicodeDecodeError: raise IDNAError('Invalid ASCII in A-label') if uts46: s = uts46_remap(s, std3_rules, False) trailing_dot = False result = [] if not strict: labels = _unicode_dots_re.split(s) else: labels = s.split('.') if not labels or labels == ['']: raise IDNAError('Empty domain') if not labels[-1]: del labels[-1] trailing_dot = True for label in labels: s = ulabel(label) if s: result.append(s) else: raise IDNAError('Empty label') if trailing_dot: result.append('') return '.'.join(result)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/idna/core.py
core.py
__version__ = '14.0.0' scripts = { 'Greek': ( 0x37000000374, 0x37500000378, 0x37a0000037e, 0x37f00000380, 0x38400000385, 0x38600000387, 0x3880000038b, 0x38c0000038d, 0x38e000003a2, 0x3a3000003e2, 0x3f000000400, 0x1d2600001d2b, 0x1d5d00001d62, 0x1d6600001d6b, 0x1dbf00001dc0, 0x1f0000001f16, 0x1f1800001f1e, 0x1f2000001f46, 0x1f4800001f4e, 0x1f5000001f58, 0x1f5900001f5a, 0x1f5b00001f5c, 0x1f5d00001f5e, 0x1f5f00001f7e, 0x1f8000001fb5, 0x1fb600001fc5, 0x1fc600001fd4, 0x1fd600001fdc, 0x1fdd00001ff0, 0x1ff200001ff5, 0x1ff600001fff, 0x212600002127, 0xab650000ab66, 0x101400001018f, 0x101a0000101a1, 0x1d2000001d246, ), 'Han': ( 0x2e8000002e9a, 0x2e9b00002ef4, 0x2f0000002fd6, 0x300500003006, 0x300700003008, 0x30210000302a, 0x30380000303c, 0x340000004dc0, 0x4e000000a000, 0xf9000000fa6e, 0xfa700000fada, 0x16fe200016fe4, 0x16ff000016ff2, 0x200000002a6e0, 0x2a7000002b739, 0x2b7400002b81e, 0x2b8200002cea2, 0x2ceb00002ebe1, 0x2f8000002fa1e, 0x300000003134b, ), 'Hebrew': ( 0x591000005c8, 0x5d0000005eb, 0x5ef000005f5, 0xfb1d0000fb37, 0xfb380000fb3d, 0xfb3e0000fb3f, 0xfb400000fb42, 0xfb430000fb45, 0xfb460000fb50, ), 'Hiragana': ( 0x304100003097, 0x309d000030a0, 0x1b0010001b120, 0x1b1500001b153, 0x1f2000001f201, ), 'Katakana': ( 0x30a1000030fb, 0x30fd00003100, 0x31f000003200, 0x32d0000032ff, 0x330000003358, 0xff660000ff70, 0xff710000ff9e, 0x1aff00001aff4, 0x1aff50001affc, 0x1affd0001afff, 0x1b0000001b001, 0x1b1200001b123, 0x1b1640001b168, ), } joining_types = { 0x600: 85, 0x601: 85, 0x602: 85, 0x603: 85, 0x604: 85, 0x605: 85, 0x608: 85, 0x60b: 85, 0x620: 68, 0x621: 85, 0x622: 82, 0x623: 82, 0x624: 82, 0x625: 82, 0x626: 68, 0x627: 82, 0x628: 68, 0x629: 82, 0x62a: 68, 0x62b: 68, 0x62c: 68, 0x62d: 68, 0x62e: 68, 0x62f: 82, 0x630: 82, 0x631: 82, 0x632: 82, 0x633: 68, 0x634: 68, 0x635: 68, 0x636: 68, 0x637: 68, 0x638: 68, 0x639: 68, 0x63a: 68, 0x63b: 68, 0x63c: 68, 0x63d: 68, 0x63e: 68, 0x63f: 68, 0x640: 67, 0x641: 68, 0x642: 68, 0x643: 68, 0x644: 68, 0x645: 68, 0x646: 68, 0x647: 68, 0x648: 82, 0x649: 68, 0x64a: 68, 0x66e: 68, 0x66f: 68, 0x671: 82, 0x672: 82, 0x673: 82, 0x674: 85, 0x675: 82, 0x676: 82, 0x677: 82, 0x678: 68, 0x679: 68, 0x67a: 68, 0x67b: 68, 0x67c: 68, 0x67d: 68, 0x67e: 68, 0x67f: 68, 0x680: 68, 0x681: 68, 0x682: 68, 0x683: 68, 0x684: 68, 0x685: 68, 0x686: 68, 0x687: 68, 0x688: 82, 0x689: 82, 0x68a: 82, 0x68b: 82, 0x68c: 82, 0x68d: 82, 0x68e: 82, 0x68f: 82, 0x690: 82, 0x691: 82, 0x692: 82, 0x693: 82, 0x694: 82, 0x695: 82, 0x696: 82, 0x697: 82, 0x698: 82, 0x699: 82, 0x69a: 68, 0x69b: 68, 0x69c: 68, 0x69d: 68, 0x69e: 68, 0x69f: 68, 0x6a0: 68, 0x6a1: 68, 0x6a2: 68, 0x6a3: 68, 0x6a4: 68, 0x6a5: 68, 0x6a6: 68, 0x6a7: 68, 0x6a8: 68, 0x6a9: 68, 0x6aa: 68, 0x6ab: 68, 0x6ac: 68, 0x6ad: 68, 0x6ae: 68, 0x6af: 68, 0x6b0: 68, 0x6b1: 68, 0x6b2: 68, 0x6b3: 68, 0x6b4: 68, 0x6b5: 68, 0x6b6: 68, 0x6b7: 68, 0x6b8: 68, 0x6b9: 68, 0x6ba: 68, 0x6bb: 68, 0x6bc: 68, 0x6bd: 68, 0x6be: 68, 0x6bf: 68, 0x6c0: 82, 0x6c1: 68, 0x6c2: 68, 0x6c3: 82, 0x6c4: 82, 0x6c5: 82, 0x6c6: 82, 0x6c7: 82, 0x6c8: 82, 0x6c9: 82, 0x6ca: 82, 0x6cb: 82, 0x6cc: 68, 0x6cd: 82, 0x6ce: 68, 0x6cf: 82, 0x6d0: 68, 0x6d1: 68, 0x6d2: 82, 0x6d3: 82, 0x6d5: 82, 0x6dd: 85, 0x6ee: 82, 0x6ef: 82, 0x6fa: 68, 0x6fb: 68, 0x6fc: 68, 0x6ff: 68, 0x70f: 84, 0x710: 82, 0x712: 68, 0x713: 68, 0x714: 68, 0x715: 82, 0x716: 82, 0x717: 82, 0x718: 82, 0x719: 82, 0x71a: 68, 0x71b: 68, 0x71c: 68, 0x71d: 68, 0x71e: 82, 0x71f: 68, 0x720: 68, 0x721: 68, 0x722: 68, 0x723: 68, 0x724: 68, 0x725: 68, 0x726: 68, 0x727: 68, 0x728: 82, 0x729: 68, 0x72a: 82, 0x72b: 68, 0x72c: 82, 0x72d: 68, 0x72e: 68, 0x72f: 82, 0x74d: 82, 0x74e: 68, 0x74f: 68, 0x750: 68, 0x751: 68, 0x752: 68, 0x753: 68, 0x754: 68, 0x755: 68, 0x756: 68, 0x757: 68, 0x758: 68, 0x759: 82, 0x75a: 82, 0x75b: 82, 0x75c: 68, 0x75d: 68, 0x75e: 68, 0x75f: 68, 0x760: 68, 0x761: 68, 0x762: 68, 0x763: 68, 0x764: 68, 0x765: 68, 0x766: 68, 0x767: 68, 0x768: 68, 0x769: 68, 0x76a: 68, 0x76b: 82, 0x76c: 82, 0x76d: 68, 0x76e: 68, 0x76f: 68, 0x770: 68, 0x771: 82, 0x772: 68, 0x773: 82, 0x774: 82, 0x775: 68, 0x776: 68, 0x777: 68, 0x778: 82, 0x779: 82, 0x77a: 68, 0x77b: 68, 0x77c: 68, 0x77d: 68, 0x77e: 68, 0x77f: 68, 0x7ca: 68, 0x7cb: 68, 0x7cc: 68, 0x7cd: 68, 0x7ce: 68, 0x7cf: 68, 0x7d0: 68, 0x7d1: 68, 0x7d2: 68, 0x7d3: 68, 0x7d4: 68, 0x7d5: 68, 0x7d6: 68, 0x7d7: 68, 0x7d8: 68, 0x7d9: 68, 0x7da: 68, 0x7db: 68, 0x7dc: 68, 0x7dd: 68, 0x7de: 68, 0x7df: 68, 0x7e0: 68, 0x7e1: 68, 0x7e2: 68, 0x7e3: 68, 0x7e4: 68, 0x7e5: 68, 0x7e6: 68, 0x7e7: 68, 0x7e8: 68, 0x7e9: 68, 0x7ea: 68, 0x7fa: 67, 0x840: 82, 0x841: 68, 0x842: 68, 0x843: 68, 0x844: 68, 0x845: 68, 0x846: 82, 0x847: 82, 0x848: 68, 0x849: 82, 0x84a: 68, 0x84b: 68, 0x84c: 68, 0x84d: 68, 0x84e: 68, 0x84f: 68, 0x850: 68, 0x851: 68, 0x852: 68, 0x853: 68, 0x854: 82, 0x855: 68, 0x856: 82, 0x857: 82, 0x858: 82, 0x860: 68, 0x861: 85, 0x862: 68, 0x863: 68, 0x864: 68, 0x865: 68, 0x866: 85, 0x867: 82, 0x868: 68, 0x869: 82, 0x86a: 82, 0x870: 82, 0x871: 82, 0x872: 82, 0x873: 82, 0x874: 82, 0x875: 82, 0x876: 82, 0x877: 82, 0x878: 82, 0x879: 82, 0x87a: 82, 0x87b: 82, 0x87c: 82, 0x87d: 82, 0x87e: 82, 0x87f: 82, 0x880: 82, 0x881: 82, 0x882: 82, 0x883: 67, 0x884: 67, 0x885: 67, 0x886: 68, 0x887: 85, 0x888: 85, 0x889: 68, 0x88a: 68, 0x88b: 68, 0x88c: 68, 0x88d: 68, 0x88e: 82, 0x890: 85, 0x891: 85, 0x8a0: 68, 0x8a1: 68, 0x8a2: 68, 0x8a3: 68, 0x8a4: 68, 0x8a5: 68, 0x8a6: 68, 0x8a7: 68, 0x8a8: 68, 0x8a9: 68, 0x8aa: 82, 0x8ab: 82, 0x8ac: 82, 0x8ad: 85, 0x8ae: 82, 0x8af: 68, 0x8b0: 68, 0x8b1: 82, 0x8b2: 82, 0x8b3: 68, 0x8b4: 68, 0x8b5: 68, 0x8b6: 68, 0x8b7: 68, 0x8b8: 68, 0x8b9: 82, 0x8ba: 68, 0x8bb: 68, 0x8bc: 68, 0x8bd: 68, 0x8be: 68, 0x8bf: 68, 0x8c0: 68, 0x8c1: 68, 0x8c2: 68, 0x8c3: 68, 0x8c4: 68, 0x8c5: 68, 0x8c6: 68, 0x8c7: 68, 0x8c8: 68, 0x8e2: 85, 0x1806: 85, 0x1807: 68, 0x180a: 67, 0x180e: 85, 0x1820: 68, 0x1821: 68, 0x1822: 68, 0x1823: 68, 0x1824: 68, 0x1825: 68, 0x1826: 68, 0x1827: 68, 0x1828: 68, 0x1829: 68, 0x182a: 68, 0x182b: 68, 0x182c: 68, 0x182d: 68, 0x182e: 68, 0x182f: 68, 0x1830: 68, 0x1831: 68, 0x1832: 68, 0x1833: 68, 0x1834: 68, 0x1835: 68, 0x1836: 68, 0x1837: 68, 0x1838: 68, 0x1839: 68, 0x183a: 68, 0x183b: 68, 0x183c: 68, 0x183d: 68, 0x183e: 68, 0x183f: 68, 0x1840: 68, 0x1841: 68, 0x1842: 68, 0x1843: 68, 0x1844: 68, 0x1845: 68, 0x1846: 68, 0x1847: 68, 0x1848: 68, 0x1849: 68, 0x184a: 68, 0x184b: 68, 0x184c: 68, 0x184d: 68, 0x184e: 68, 0x184f: 68, 0x1850: 68, 0x1851: 68, 0x1852: 68, 0x1853: 68, 0x1854: 68, 0x1855: 68, 0x1856: 68, 0x1857: 68, 0x1858: 68, 0x1859: 68, 0x185a: 68, 0x185b: 68, 0x185c: 68, 0x185d: 68, 0x185e: 68, 0x185f: 68, 0x1860: 68, 0x1861: 68, 0x1862: 68, 0x1863: 68, 0x1864: 68, 0x1865: 68, 0x1866: 68, 0x1867: 68, 0x1868: 68, 0x1869: 68, 0x186a: 68, 0x186b: 68, 0x186c: 68, 0x186d: 68, 0x186e: 68, 0x186f: 68, 0x1870: 68, 0x1871: 68, 0x1872: 68, 0x1873: 68, 0x1874: 68, 0x1875: 68, 0x1876: 68, 0x1877: 68, 0x1878: 68, 0x1880: 85, 0x1881: 85, 0x1882: 85, 0x1883: 85, 0x1884: 85, 0x1885: 84, 0x1886: 84, 0x1887: 68, 0x1888: 68, 0x1889: 68, 0x188a: 68, 0x188b: 68, 0x188c: 68, 0x188d: 68, 0x188e: 68, 0x188f: 68, 0x1890: 68, 0x1891: 68, 0x1892: 68, 0x1893: 68, 0x1894: 68, 0x1895: 68, 0x1896: 68, 0x1897: 68, 0x1898: 68, 0x1899: 68, 0x189a: 68, 0x189b: 68, 0x189c: 68, 0x189d: 68, 0x189e: 68, 0x189f: 68, 0x18a0: 68, 0x18a1: 68, 0x18a2: 68, 0x18a3: 68, 0x18a4: 68, 0x18a5: 68, 0x18a6: 68, 0x18a7: 68, 0x18a8: 68, 0x18aa: 68, 0x200c: 85, 0x200d: 67, 0x202f: 85, 0x2066: 85, 0x2067: 85, 0x2068: 85, 0x2069: 85, 0xa840: 68, 0xa841: 68, 0xa842: 68, 0xa843: 68, 0xa844: 68, 0xa845: 68, 0xa846: 68, 0xa847: 68, 0xa848: 68, 0xa849: 68, 0xa84a: 68, 0xa84b: 68, 0xa84c: 68, 0xa84d: 68, 0xa84e: 68, 0xa84f: 68, 0xa850: 68, 0xa851: 68, 0xa852: 68, 0xa853: 68, 0xa854: 68, 0xa855: 68, 0xa856: 68, 0xa857: 68, 0xa858: 68, 0xa859: 68, 0xa85a: 68, 0xa85b: 68, 0xa85c: 68, 0xa85d: 68, 0xa85e: 68, 0xa85f: 68, 0xa860: 68, 0xa861: 68, 0xa862: 68, 0xa863: 68, 0xa864: 68, 0xa865: 68, 0xa866: 68, 0xa867: 68, 0xa868: 68, 0xa869: 68, 0xa86a: 68, 0xa86b: 68, 0xa86c: 68, 0xa86d: 68, 0xa86e: 68, 0xa86f: 68, 0xa870: 68, 0xa871: 68, 0xa872: 76, 0xa873: 85, 0x10ac0: 68, 0x10ac1: 68, 0x10ac2: 68, 0x10ac3: 68, 0x10ac4: 68, 0x10ac5: 82, 0x10ac6: 85, 0x10ac7: 82, 0x10ac8: 85, 0x10ac9: 82, 0x10aca: 82, 0x10acb: 85, 0x10acc: 85, 0x10acd: 76, 0x10ace: 82, 0x10acf: 82, 0x10ad0: 82, 0x10ad1: 82, 0x10ad2: 82, 0x10ad3: 68, 0x10ad4: 68, 0x10ad5: 68, 0x10ad6: 68, 0x10ad7: 76, 0x10ad8: 68, 0x10ad9: 68, 0x10ada: 68, 0x10adb: 68, 0x10adc: 68, 0x10add: 82, 0x10ade: 68, 0x10adf: 68, 0x10ae0: 68, 0x10ae1: 82, 0x10ae2: 85, 0x10ae3: 85, 0x10ae4: 82, 0x10aeb: 68, 0x10aec: 68, 0x10aed: 68, 0x10aee: 68, 0x10aef: 82, 0x10b80: 68, 0x10b81: 82, 0x10b82: 68, 0x10b83: 82, 0x10b84: 82, 0x10b85: 82, 0x10b86: 68, 0x10b87: 68, 0x10b88: 68, 0x10b89: 82, 0x10b8a: 68, 0x10b8b: 68, 0x10b8c: 82, 0x10b8d: 68, 0x10b8e: 82, 0x10b8f: 82, 0x10b90: 68, 0x10b91: 82, 0x10ba9: 82, 0x10baa: 82, 0x10bab: 82, 0x10bac: 82, 0x10bad: 68, 0x10bae: 68, 0x10baf: 85, 0x10d00: 76, 0x10d01: 68, 0x10d02: 68, 0x10d03: 68, 0x10d04: 68, 0x10d05: 68, 0x10d06: 68, 0x10d07: 68, 0x10d08: 68, 0x10d09: 68, 0x10d0a: 68, 0x10d0b: 68, 0x10d0c: 68, 0x10d0d: 68, 0x10d0e: 68, 0x10d0f: 68, 0x10d10: 68, 0x10d11: 68, 0x10d12: 68, 0x10d13: 68, 0x10d14: 68, 0x10d15: 68, 0x10d16: 68, 0x10d17: 68, 0x10d18: 68, 0x10d19: 68, 0x10d1a: 68, 0x10d1b: 68, 0x10d1c: 68, 0x10d1d: 68, 0x10d1e: 68, 0x10d1f: 68, 0x10d20: 68, 0x10d21: 68, 0x10d22: 82, 0x10d23: 68, 0x10f30: 68, 0x10f31: 68, 0x10f32: 68, 0x10f33: 82, 0x10f34: 68, 0x10f35: 68, 0x10f36: 68, 0x10f37: 68, 0x10f38: 68, 0x10f39: 68, 0x10f3a: 68, 0x10f3b: 68, 0x10f3c: 68, 0x10f3d: 68, 0x10f3e: 68, 0x10f3f: 68, 0x10f40: 68, 0x10f41: 68, 0x10f42: 68, 0x10f43: 68, 0x10f44: 68, 0x10f45: 85, 0x10f51: 68, 0x10f52: 68, 0x10f53: 68, 0x10f54: 82, 0x10f70: 68, 0x10f71: 68, 0x10f72: 68, 0x10f73: 68, 0x10f74: 82, 0x10f75: 82, 0x10f76: 68, 0x10f77: 68, 0x10f78: 68, 0x10f79: 68, 0x10f7a: 68, 0x10f7b: 68, 0x10f7c: 68, 0x10f7d: 68, 0x10f7e: 68, 0x10f7f: 68, 0x10f80: 68, 0x10f81: 68, 0x10fb0: 68, 0x10fb1: 85, 0x10fb2: 68, 0x10fb3: 68, 0x10fb4: 82, 0x10fb5: 82, 0x10fb6: 82, 0x10fb7: 85, 0x10fb8: 68, 0x10fb9: 82, 0x10fba: 82, 0x10fbb: 68, 0x10fbc: 68, 0x10fbd: 82, 0x10fbe: 68, 0x10fbf: 68, 0x10fc0: 85, 0x10fc1: 68, 0x10fc2: 82, 0x10fc3: 82, 0x10fc4: 68, 0x10fc5: 85, 0x10fc6: 85, 0x10fc7: 85, 0x10fc8: 85, 0x10fc9: 82, 0x10fca: 68, 0x10fcb: 76, 0x110bd: 85, 0x110cd: 85, 0x1e900: 68, 0x1e901: 68, 0x1e902: 68, 0x1e903: 68, 0x1e904: 68, 0x1e905: 68, 0x1e906: 68, 0x1e907: 68, 0x1e908: 68, 0x1e909: 68, 0x1e90a: 68, 0x1e90b: 68, 0x1e90c: 68, 0x1e90d: 68, 0x1e90e: 68, 0x1e90f: 68, 0x1e910: 68, 0x1e911: 68, 0x1e912: 68, 0x1e913: 68, 0x1e914: 68, 0x1e915: 68, 0x1e916: 68, 0x1e917: 68, 0x1e918: 68, 0x1e919: 68, 0x1e91a: 68, 0x1e91b: 68, 0x1e91c: 68, 0x1e91d: 68, 0x1e91e: 68, 0x1e91f: 68, 0x1e920: 68, 0x1e921: 68, 0x1e922: 68, 0x1e923: 68, 0x1e924: 68, 0x1e925: 68, 0x1e926: 68, 0x1e927: 68, 0x1e928: 68, 0x1e929: 68, 0x1e92a: 68, 0x1e92b: 68, 0x1e92c: 68, 0x1e92d: 68, 0x1e92e: 68, 0x1e92f: 68, 0x1e930: 68, 0x1e931: 68, 0x1e932: 68, 0x1e933: 68, 0x1e934: 68, 0x1e935: 68, 0x1e936: 68, 0x1e937: 68, 0x1e938: 68, 0x1e939: 68, 0x1e93a: 68, 0x1e93b: 68, 0x1e93c: 68, 0x1e93d: 68, 0x1e93e: 68, 0x1e93f: 68, 0x1e940: 68, 0x1e941: 68, 0x1e942: 68, 0x1e943: 68, 0x1e94b: 84, } codepoint_classes = { 'PVALID': ( 0x2d0000002e, 0x300000003a, 0x610000007b, 0xdf000000f7, 0xf800000100, 0x10100000102, 0x10300000104, 0x10500000106, 0x10700000108, 0x1090000010a, 0x10b0000010c, 0x10d0000010e, 0x10f00000110, 0x11100000112, 0x11300000114, 0x11500000116, 0x11700000118, 0x1190000011a, 0x11b0000011c, 0x11d0000011e, 0x11f00000120, 0x12100000122, 0x12300000124, 0x12500000126, 0x12700000128, 0x1290000012a, 0x12b0000012c, 0x12d0000012e, 0x12f00000130, 0x13100000132, 0x13500000136, 0x13700000139, 0x13a0000013b, 0x13c0000013d, 0x13e0000013f, 0x14200000143, 0x14400000145, 0x14600000147, 0x14800000149, 0x14b0000014c, 0x14d0000014e, 0x14f00000150, 0x15100000152, 0x15300000154, 0x15500000156, 0x15700000158, 0x1590000015a, 0x15b0000015c, 0x15d0000015e, 0x15f00000160, 0x16100000162, 0x16300000164, 0x16500000166, 0x16700000168, 0x1690000016a, 0x16b0000016c, 0x16d0000016e, 0x16f00000170, 0x17100000172, 0x17300000174, 0x17500000176, 0x17700000178, 0x17a0000017b, 0x17c0000017d, 0x17e0000017f, 0x18000000181, 0x18300000184, 0x18500000186, 0x18800000189, 0x18c0000018e, 0x19200000193, 0x19500000196, 0x1990000019c, 0x19e0000019f, 0x1a1000001a2, 0x1a3000001a4, 0x1a5000001a6, 0x1a8000001a9, 0x1aa000001ac, 0x1ad000001ae, 0x1b0000001b1, 0x1b4000001b5, 0x1b6000001b7, 0x1b9000001bc, 0x1bd000001c4, 0x1ce000001cf, 0x1d0000001d1, 0x1d2000001d3, 0x1d4000001d5, 0x1d6000001d7, 0x1d8000001d9, 0x1da000001db, 0x1dc000001de, 0x1df000001e0, 0x1e1000001e2, 0x1e3000001e4, 0x1e5000001e6, 0x1e7000001e8, 0x1e9000001ea, 0x1eb000001ec, 0x1ed000001ee, 0x1ef000001f1, 0x1f5000001f6, 0x1f9000001fa, 0x1fb000001fc, 0x1fd000001fe, 0x1ff00000200, 0x20100000202, 0x20300000204, 0x20500000206, 0x20700000208, 0x2090000020a, 0x20b0000020c, 0x20d0000020e, 0x20f00000210, 0x21100000212, 0x21300000214, 0x21500000216, 0x21700000218, 0x2190000021a, 0x21b0000021c, 0x21d0000021e, 0x21f00000220, 0x22100000222, 0x22300000224, 0x22500000226, 0x22700000228, 0x2290000022a, 0x22b0000022c, 0x22d0000022e, 0x22f00000230, 0x23100000232, 0x2330000023a, 0x23c0000023d, 0x23f00000241, 0x24200000243, 0x24700000248, 0x2490000024a, 0x24b0000024c, 0x24d0000024e, 0x24f000002b0, 0x2b9000002c2, 0x2c6000002d2, 0x2ec000002ed, 0x2ee000002ef, 0x30000000340, 0x34200000343, 0x3460000034f, 0x35000000370, 0x37100000372, 0x37300000374, 0x37700000378, 0x37b0000037e, 0x39000000391, 0x3ac000003cf, 0x3d7000003d8, 0x3d9000003da, 0x3db000003dc, 0x3dd000003de, 0x3df000003e0, 0x3e1000003e2, 0x3e3000003e4, 0x3e5000003e6, 0x3e7000003e8, 0x3e9000003ea, 0x3eb000003ec, 0x3ed000003ee, 0x3ef000003f0, 0x3f3000003f4, 0x3f8000003f9, 0x3fb000003fd, 0x43000000460, 0x46100000462, 0x46300000464, 0x46500000466, 0x46700000468, 0x4690000046a, 0x46b0000046c, 0x46d0000046e, 0x46f00000470, 0x47100000472, 0x47300000474, 0x47500000476, 0x47700000478, 0x4790000047a, 0x47b0000047c, 0x47d0000047e, 0x47f00000480, 0x48100000482, 0x48300000488, 0x48b0000048c, 0x48d0000048e, 0x48f00000490, 0x49100000492, 0x49300000494, 0x49500000496, 0x49700000498, 0x4990000049a, 0x49b0000049c, 0x49d0000049e, 0x49f000004a0, 0x4a1000004a2, 0x4a3000004a4, 0x4a5000004a6, 0x4a7000004a8, 0x4a9000004aa, 0x4ab000004ac, 0x4ad000004ae, 0x4af000004b0, 0x4b1000004b2, 0x4b3000004b4, 0x4b5000004b6, 0x4b7000004b8, 0x4b9000004ba, 0x4bb000004bc, 0x4bd000004be, 0x4bf000004c0, 0x4c2000004c3, 0x4c4000004c5, 0x4c6000004c7, 0x4c8000004c9, 0x4ca000004cb, 0x4cc000004cd, 0x4ce000004d0, 0x4d1000004d2, 0x4d3000004d4, 0x4d5000004d6, 0x4d7000004d8, 0x4d9000004da, 0x4db000004dc, 0x4dd000004de, 0x4df000004e0, 0x4e1000004e2, 0x4e3000004e4, 0x4e5000004e6, 0x4e7000004e8, 0x4e9000004ea, 0x4eb000004ec, 0x4ed000004ee, 0x4ef000004f0, 0x4f1000004f2, 0x4f3000004f4, 0x4f5000004f6, 0x4f7000004f8, 0x4f9000004fa, 0x4fb000004fc, 0x4fd000004fe, 0x4ff00000500, 0x50100000502, 0x50300000504, 0x50500000506, 0x50700000508, 0x5090000050a, 0x50b0000050c, 0x50d0000050e, 0x50f00000510, 0x51100000512, 0x51300000514, 0x51500000516, 0x51700000518, 0x5190000051a, 0x51b0000051c, 0x51d0000051e, 0x51f00000520, 0x52100000522, 0x52300000524, 0x52500000526, 0x52700000528, 0x5290000052a, 0x52b0000052c, 0x52d0000052e, 0x52f00000530, 0x5590000055a, 0x56000000587, 0x58800000589, 0x591000005be, 0x5bf000005c0, 0x5c1000005c3, 0x5c4000005c6, 0x5c7000005c8, 0x5d0000005eb, 0x5ef000005f3, 0x6100000061b, 0x62000000640, 0x64100000660, 0x66e00000675, 0x679000006d4, 0x6d5000006dd, 0x6df000006e9, 0x6ea000006f0, 0x6fa00000700, 0x7100000074b, 0x74d000007b2, 0x7c0000007f6, 0x7fd000007fe, 0x8000000082e, 0x8400000085c, 0x8600000086b, 0x87000000888, 0x8890000088f, 0x898000008e2, 0x8e300000958, 0x96000000964, 0x96600000970, 0x97100000984, 0x9850000098d, 0x98f00000991, 0x993000009a9, 0x9aa000009b1, 0x9b2000009b3, 0x9b6000009ba, 0x9bc000009c5, 0x9c7000009c9, 0x9cb000009cf, 0x9d7000009d8, 0x9e0000009e4, 0x9e6000009f2, 0x9fc000009fd, 0x9fe000009ff, 0xa0100000a04, 0xa0500000a0b, 0xa0f00000a11, 0xa1300000a29, 0xa2a00000a31, 0xa3200000a33, 0xa3500000a36, 0xa3800000a3a, 0xa3c00000a3d, 0xa3e00000a43, 0xa4700000a49, 0xa4b00000a4e, 0xa5100000a52, 0xa5c00000a5d, 0xa6600000a76, 0xa8100000a84, 0xa8500000a8e, 0xa8f00000a92, 0xa9300000aa9, 0xaaa00000ab1, 0xab200000ab4, 0xab500000aba, 0xabc00000ac6, 0xac700000aca, 0xacb00000ace, 0xad000000ad1, 0xae000000ae4, 0xae600000af0, 0xaf900000b00, 0xb0100000b04, 0xb0500000b0d, 0xb0f00000b11, 0xb1300000b29, 0xb2a00000b31, 0xb3200000b34, 0xb3500000b3a, 0xb3c00000b45, 0xb4700000b49, 0xb4b00000b4e, 0xb5500000b58, 0xb5f00000b64, 0xb6600000b70, 0xb7100000b72, 0xb8200000b84, 0xb8500000b8b, 0xb8e00000b91, 0xb9200000b96, 0xb9900000b9b, 0xb9c00000b9d, 0xb9e00000ba0, 0xba300000ba5, 0xba800000bab, 0xbae00000bba, 0xbbe00000bc3, 0xbc600000bc9, 0xbca00000bce, 0xbd000000bd1, 0xbd700000bd8, 0xbe600000bf0, 0xc0000000c0d, 0xc0e00000c11, 0xc1200000c29, 0xc2a00000c3a, 0xc3c00000c45, 0xc4600000c49, 0xc4a00000c4e, 0xc5500000c57, 0xc5800000c5b, 0xc5d00000c5e, 0xc6000000c64, 0xc6600000c70, 0xc8000000c84, 0xc8500000c8d, 0xc8e00000c91, 0xc9200000ca9, 0xcaa00000cb4, 0xcb500000cba, 0xcbc00000cc5, 0xcc600000cc9, 0xcca00000cce, 0xcd500000cd7, 0xcdd00000cdf, 0xce000000ce4, 0xce600000cf0, 0xcf100000cf3, 0xd0000000d0d, 0xd0e00000d11, 0xd1200000d45, 0xd4600000d49, 0xd4a00000d4f, 0xd5400000d58, 0xd5f00000d64, 0xd6600000d70, 0xd7a00000d80, 0xd8100000d84, 0xd8500000d97, 0xd9a00000db2, 0xdb300000dbc, 0xdbd00000dbe, 0xdc000000dc7, 0xdca00000dcb, 0xdcf00000dd5, 0xdd600000dd7, 0xdd800000de0, 0xde600000df0, 0xdf200000df4, 0xe0100000e33, 0xe3400000e3b, 0xe4000000e4f, 0xe5000000e5a, 0xe8100000e83, 0xe8400000e85, 0xe8600000e8b, 0xe8c00000ea4, 0xea500000ea6, 0xea700000eb3, 0xeb400000ebe, 0xec000000ec5, 0xec600000ec7, 0xec800000ece, 0xed000000eda, 0xede00000ee0, 0xf0000000f01, 0xf0b00000f0c, 0xf1800000f1a, 0xf2000000f2a, 0xf3500000f36, 0xf3700000f38, 0xf3900000f3a, 0xf3e00000f43, 0xf4400000f48, 0xf4900000f4d, 0xf4e00000f52, 0xf5300000f57, 0xf5800000f5c, 0xf5d00000f69, 0xf6a00000f6d, 0xf7100000f73, 0xf7400000f75, 0xf7a00000f81, 0xf8200000f85, 0xf8600000f93, 0xf9400000f98, 0xf9900000f9d, 0xf9e00000fa2, 0xfa300000fa7, 0xfa800000fac, 0xfad00000fb9, 0xfba00000fbd, 0xfc600000fc7, 0x10000000104a, 0x10500000109e, 0x10d0000010fb, 0x10fd00001100, 0x120000001249, 0x124a0000124e, 0x125000001257, 0x125800001259, 0x125a0000125e, 0x126000001289, 0x128a0000128e, 0x1290000012b1, 0x12b2000012b6, 0x12b8000012bf, 0x12c0000012c1, 0x12c2000012c6, 0x12c8000012d7, 0x12d800001311, 0x131200001316, 0x13180000135b, 0x135d00001360, 0x138000001390, 0x13a0000013f6, 0x14010000166d, 0x166f00001680, 0x16810000169b, 0x16a0000016eb, 0x16f1000016f9, 0x170000001716, 0x171f00001735, 0x174000001754, 0x17600000176d, 0x176e00001771, 0x177200001774, 0x1780000017b4, 0x17b6000017d4, 0x17d7000017d8, 0x17dc000017de, 0x17e0000017ea, 0x18100000181a, 0x182000001879, 0x1880000018ab, 0x18b0000018f6, 0x19000000191f, 0x19200000192c, 0x19300000193c, 0x19460000196e, 0x197000001975, 0x1980000019ac, 0x19b0000019ca, 0x19d0000019da, 0x1a0000001a1c, 0x1a2000001a5f, 0x1a6000001a7d, 0x1a7f00001a8a, 0x1a9000001a9a, 0x1aa700001aa8, 0x1ab000001abe, 0x1abf00001acf, 0x1b0000001b4d, 0x1b5000001b5a, 0x1b6b00001b74, 0x1b8000001bf4, 0x1c0000001c38, 0x1c4000001c4a, 0x1c4d00001c7e, 0x1cd000001cd3, 0x1cd400001cfb, 0x1d0000001d2c, 0x1d2f00001d30, 0x1d3b00001d3c, 0x1d4e00001d4f, 0x1d6b00001d78, 0x1d7900001d9b, 0x1dc000001e00, 0x1e0100001e02, 0x1e0300001e04, 0x1e0500001e06, 0x1e0700001e08, 0x1e0900001e0a, 0x1e0b00001e0c, 0x1e0d00001e0e, 0x1e0f00001e10, 0x1e1100001e12, 0x1e1300001e14, 0x1e1500001e16, 0x1e1700001e18, 0x1e1900001e1a, 0x1e1b00001e1c, 0x1e1d00001e1e, 0x1e1f00001e20, 0x1e2100001e22, 0x1e2300001e24, 0x1e2500001e26, 0x1e2700001e28, 0x1e2900001e2a, 0x1e2b00001e2c, 0x1e2d00001e2e, 0x1e2f00001e30, 0x1e3100001e32, 0x1e3300001e34, 0x1e3500001e36, 0x1e3700001e38, 0x1e3900001e3a, 0x1e3b00001e3c, 0x1e3d00001e3e, 0x1e3f00001e40, 0x1e4100001e42, 0x1e4300001e44, 0x1e4500001e46, 0x1e4700001e48, 0x1e4900001e4a, 0x1e4b00001e4c, 0x1e4d00001e4e, 0x1e4f00001e50, 0x1e5100001e52, 0x1e5300001e54, 0x1e5500001e56, 0x1e5700001e58, 0x1e5900001e5a, 0x1e5b00001e5c, 0x1e5d00001e5e, 0x1e5f00001e60, 0x1e6100001e62, 0x1e6300001e64, 0x1e6500001e66, 0x1e6700001e68, 0x1e6900001e6a, 0x1e6b00001e6c, 0x1e6d00001e6e, 0x1e6f00001e70, 0x1e7100001e72, 0x1e7300001e74, 0x1e7500001e76, 0x1e7700001e78, 0x1e7900001e7a, 0x1e7b00001e7c, 0x1e7d00001e7e, 0x1e7f00001e80, 0x1e8100001e82, 0x1e8300001e84, 0x1e8500001e86, 0x1e8700001e88, 0x1e8900001e8a, 0x1e8b00001e8c, 0x1e8d00001e8e, 0x1e8f00001e90, 0x1e9100001e92, 0x1e9300001e94, 0x1e9500001e9a, 0x1e9c00001e9e, 0x1e9f00001ea0, 0x1ea100001ea2, 0x1ea300001ea4, 0x1ea500001ea6, 0x1ea700001ea8, 0x1ea900001eaa, 0x1eab00001eac, 0x1ead00001eae, 0x1eaf00001eb0, 0x1eb100001eb2, 0x1eb300001eb4, 0x1eb500001eb6, 0x1eb700001eb8, 0x1eb900001eba, 0x1ebb00001ebc, 0x1ebd00001ebe, 0x1ebf00001ec0, 0x1ec100001ec2, 0x1ec300001ec4, 0x1ec500001ec6, 0x1ec700001ec8, 0x1ec900001eca, 0x1ecb00001ecc, 0x1ecd00001ece, 0x1ecf00001ed0, 0x1ed100001ed2, 0x1ed300001ed4, 0x1ed500001ed6, 0x1ed700001ed8, 0x1ed900001eda, 0x1edb00001edc, 0x1edd00001ede, 0x1edf00001ee0, 0x1ee100001ee2, 0x1ee300001ee4, 0x1ee500001ee6, 0x1ee700001ee8, 0x1ee900001eea, 0x1eeb00001eec, 0x1eed00001eee, 0x1eef00001ef0, 0x1ef100001ef2, 0x1ef300001ef4, 0x1ef500001ef6, 0x1ef700001ef8, 0x1ef900001efa, 0x1efb00001efc, 0x1efd00001efe, 0x1eff00001f08, 0x1f1000001f16, 0x1f2000001f28, 0x1f3000001f38, 0x1f4000001f46, 0x1f5000001f58, 0x1f6000001f68, 0x1f7000001f71, 0x1f7200001f73, 0x1f7400001f75, 0x1f7600001f77, 0x1f7800001f79, 0x1f7a00001f7b, 0x1f7c00001f7d, 0x1fb000001fb2, 0x1fb600001fb7, 0x1fc600001fc7, 0x1fd000001fd3, 0x1fd600001fd8, 0x1fe000001fe3, 0x1fe400001fe8, 0x1ff600001ff7, 0x214e0000214f, 0x218400002185, 0x2c3000002c60, 0x2c6100002c62, 0x2c6500002c67, 0x2c6800002c69, 0x2c6a00002c6b, 0x2c6c00002c6d, 0x2c7100002c72, 0x2c7300002c75, 0x2c7600002c7c, 0x2c8100002c82, 0x2c8300002c84, 0x2c8500002c86, 0x2c8700002c88, 0x2c8900002c8a, 0x2c8b00002c8c, 0x2c8d00002c8e, 0x2c8f00002c90, 0x2c9100002c92, 0x2c9300002c94, 0x2c9500002c96, 0x2c9700002c98, 0x2c9900002c9a, 0x2c9b00002c9c, 0x2c9d00002c9e, 0x2c9f00002ca0, 0x2ca100002ca2, 0x2ca300002ca4, 0x2ca500002ca6, 0x2ca700002ca8, 0x2ca900002caa, 0x2cab00002cac, 0x2cad00002cae, 0x2caf00002cb0, 0x2cb100002cb2, 0x2cb300002cb4, 0x2cb500002cb6, 0x2cb700002cb8, 0x2cb900002cba, 0x2cbb00002cbc, 0x2cbd00002cbe, 0x2cbf00002cc0, 0x2cc100002cc2, 0x2cc300002cc4, 0x2cc500002cc6, 0x2cc700002cc8, 0x2cc900002cca, 0x2ccb00002ccc, 0x2ccd00002cce, 0x2ccf00002cd0, 0x2cd100002cd2, 0x2cd300002cd4, 0x2cd500002cd6, 0x2cd700002cd8, 0x2cd900002cda, 0x2cdb00002cdc, 0x2cdd00002cde, 0x2cdf00002ce0, 0x2ce100002ce2, 0x2ce300002ce5, 0x2cec00002ced, 0x2cee00002cf2, 0x2cf300002cf4, 0x2d0000002d26, 0x2d2700002d28, 0x2d2d00002d2e, 0x2d3000002d68, 0x2d7f00002d97, 0x2da000002da7, 0x2da800002daf, 0x2db000002db7, 0x2db800002dbf, 0x2dc000002dc7, 0x2dc800002dcf, 0x2dd000002dd7, 0x2dd800002ddf, 0x2de000002e00, 0x2e2f00002e30, 0x300500003008, 0x302a0000302e, 0x303c0000303d, 0x304100003097, 0x30990000309b, 0x309d0000309f, 0x30a1000030fb, 0x30fc000030ff, 0x310500003130, 0x31a0000031c0, 0x31f000003200, 0x340000004dc0, 0x4e000000a48d, 0xa4d00000a4fe, 0xa5000000a60d, 0xa6100000a62c, 0xa6410000a642, 0xa6430000a644, 0xa6450000a646, 0xa6470000a648, 0xa6490000a64a, 0xa64b0000a64c, 0xa64d0000a64e, 0xa64f0000a650, 0xa6510000a652, 0xa6530000a654, 0xa6550000a656, 0xa6570000a658, 0xa6590000a65a, 0xa65b0000a65c, 0xa65d0000a65e, 0xa65f0000a660, 0xa6610000a662, 0xa6630000a664, 0xa6650000a666, 0xa6670000a668, 0xa6690000a66a, 0xa66b0000a66c, 0xa66d0000a670, 0xa6740000a67e, 0xa67f0000a680, 0xa6810000a682, 0xa6830000a684, 0xa6850000a686, 0xa6870000a688, 0xa6890000a68a, 0xa68b0000a68c, 0xa68d0000a68e, 0xa68f0000a690, 0xa6910000a692, 0xa6930000a694, 0xa6950000a696, 0xa6970000a698, 0xa6990000a69a, 0xa69b0000a69c, 0xa69e0000a6e6, 0xa6f00000a6f2, 0xa7170000a720, 0xa7230000a724, 0xa7250000a726, 0xa7270000a728, 0xa7290000a72a, 0xa72b0000a72c, 0xa72d0000a72e, 0xa72f0000a732, 0xa7330000a734, 0xa7350000a736, 0xa7370000a738, 0xa7390000a73a, 0xa73b0000a73c, 0xa73d0000a73e, 0xa73f0000a740, 0xa7410000a742, 0xa7430000a744, 0xa7450000a746, 0xa7470000a748, 0xa7490000a74a, 0xa74b0000a74c, 0xa74d0000a74e, 0xa74f0000a750, 0xa7510000a752, 0xa7530000a754, 0xa7550000a756, 0xa7570000a758, 0xa7590000a75a, 0xa75b0000a75c, 0xa75d0000a75e, 0xa75f0000a760, 0xa7610000a762, 0xa7630000a764, 0xa7650000a766, 0xa7670000a768, 0xa7690000a76a, 0xa76b0000a76c, 0xa76d0000a76e, 0xa76f0000a770, 0xa7710000a779, 0xa77a0000a77b, 0xa77c0000a77d, 0xa77f0000a780, 0xa7810000a782, 0xa7830000a784, 0xa7850000a786, 0xa7870000a789, 0xa78c0000a78d, 0xa78e0000a790, 0xa7910000a792, 0xa7930000a796, 0xa7970000a798, 0xa7990000a79a, 0xa79b0000a79c, 0xa79d0000a79e, 0xa79f0000a7a0, 0xa7a10000a7a2, 0xa7a30000a7a4, 0xa7a50000a7a6, 0xa7a70000a7a8, 0xa7a90000a7aa, 0xa7af0000a7b0, 0xa7b50000a7b6, 0xa7b70000a7b8, 0xa7b90000a7ba, 0xa7bb0000a7bc, 0xa7bd0000a7be, 0xa7bf0000a7c0, 0xa7c10000a7c2, 0xa7c30000a7c4, 0xa7c80000a7c9, 0xa7ca0000a7cb, 0xa7d10000a7d2, 0xa7d30000a7d4, 0xa7d50000a7d6, 0xa7d70000a7d8, 0xa7d90000a7da, 0xa7f20000a7f5, 0xa7f60000a7f8, 0xa7fa0000a828, 0xa82c0000a82d, 0xa8400000a874, 0xa8800000a8c6, 0xa8d00000a8da, 0xa8e00000a8f8, 0xa8fb0000a8fc, 0xa8fd0000a92e, 0xa9300000a954, 0xa9800000a9c1, 0xa9cf0000a9da, 0xa9e00000a9ff, 0xaa000000aa37, 0xaa400000aa4e, 0xaa500000aa5a, 0xaa600000aa77, 0xaa7a0000aac3, 0xaadb0000aade, 0xaae00000aaf0, 0xaaf20000aaf7, 0xab010000ab07, 0xab090000ab0f, 0xab110000ab17, 0xab200000ab27, 0xab280000ab2f, 0xab300000ab5b, 0xab600000ab6a, 0xabc00000abeb, 0xabec0000abee, 0xabf00000abfa, 0xac000000d7a4, 0xfa0e0000fa10, 0xfa110000fa12, 0xfa130000fa15, 0xfa1f0000fa20, 0xfa210000fa22, 0xfa230000fa25, 0xfa270000fa2a, 0xfb1e0000fb1f, 0xfe200000fe30, 0xfe730000fe74, 0x100000001000c, 0x1000d00010027, 0x100280001003b, 0x1003c0001003e, 0x1003f0001004e, 0x100500001005e, 0x10080000100fb, 0x101fd000101fe, 0x102800001029d, 0x102a0000102d1, 0x102e0000102e1, 0x1030000010320, 0x1032d00010341, 0x103420001034a, 0x103500001037b, 0x103800001039e, 0x103a0000103c4, 0x103c8000103d0, 0x104280001049e, 0x104a0000104aa, 0x104d8000104fc, 0x1050000010528, 0x1053000010564, 0x10597000105a2, 0x105a3000105b2, 0x105b3000105ba, 0x105bb000105bd, 0x1060000010737, 0x1074000010756, 0x1076000010768, 0x1078000010786, 0x10787000107b1, 0x107b2000107bb, 0x1080000010806, 0x1080800010809, 0x1080a00010836, 0x1083700010839, 0x1083c0001083d, 0x1083f00010856, 0x1086000010877, 0x108800001089f, 0x108e0000108f3, 0x108f4000108f6, 0x1090000010916, 0x109200001093a, 0x10980000109b8, 0x109be000109c0, 0x10a0000010a04, 0x10a0500010a07, 0x10a0c00010a14, 0x10a1500010a18, 0x10a1900010a36, 0x10a3800010a3b, 0x10a3f00010a40, 0x10a6000010a7d, 0x10a8000010a9d, 0x10ac000010ac8, 0x10ac900010ae7, 0x10b0000010b36, 0x10b4000010b56, 0x10b6000010b73, 0x10b8000010b92, 0x10c0000010c49, 0x10cc000010cf3, 0x10d0000010d28, 0x10d3000010d3a, 0x10e8000010eaa, 0x10eab00010ead, 0x10eb000010eb2, 0x10f0000010f1d, 0x10f2700010f28, 0x10f3000010f51, 0x10f7000010f86, 0x10fb000010fc5, 0x10fe000010ff7, 0x1100000011047, 0x1106600011076, 0x1107f000110bb, 0x110c2000110c3, 0x110d0000110e9, 0x110f0000110fa, 0x1110000011135, 0x1113600011140, 0x1114400011148, 0x1115000011174, 0x1117600011177, 0x11180000111c5, 0x111c9000111cd, 0x111ce000111db, 0x111dc000111dd, 0x1120000011212, 0x1121300011238, 0x1123e0001123f, 0x1128000011287, 0x1128800011289, 0x1128a0001128e, 0x1128f0001129e, 0x1129f000112a9, 0x112b0000112eb, 0x112f0000112fa, 0x1130000011304, 0x113050001130d, 0x1130f00011311, 0x1131300011329, 0x1132a00011331, 0x1133200011334, 0x113350001133a, 0x1133b00011345, 0x1134700011349, 0x1134b0001134e, 0x1135000011351, 0x1135700011358, 0x1135d00011364, 0x113660001136d, 0x1137000011375, 0x114000001144b, 0x114500001145a, 0x1145e00011462, 0x11480000114c6, 0x114c7000114c8, 0x114d0000114da, 0x11580000115b6, 0x115b8000115c1, 0x115d8000115de, 0x1160000011641, 0x1164400011645, 0x116500001165a, 0x11680000116b9, 0x116c0000116ca, 0x117000001171b, 0x1171d0001172c, 0x117300001173a, 0x1174000011747, 0x118000001183b, 0x118c0000118ea, 0x118ff00011907, 0x119090001190a, 0x1190c00011914, 0x1191500011917, 0x1191800011936, 0x1193700011939, 0x1193b00011944, 0x119500001195a, 0x119a0000119a8, 0x119aa000119d8, 0x119da000119e2, 0x119e3000119e5, 0x11a0000011a3f, 0x11a4700011a48, 0x11a5000011a9a, 0x11a9d00011a9e, 0x11ab000011af9, 0x11c0000011c09, 0x11c0a00011c37, 0x11c3800011c41, 0x11c5000011c5a, 0x11c7200011c90, 0x11c9200011ca8, 0x11ca900011cb7, 0x11d0000011d07, 0x11d0800011d0a, 0x11d0b00011d37, 0x11d3a00011d3b, 0x11d3c00011d3e, 0x11d3f00011d48, 0x11d5000011d5a, 0x11d6000011d66, 0x11d6700011d69, 0x11d6a00011d8f, 0x11d9000011d92, 0x11d9300011d99, 0x11da000011daa, 0x11ee000011ef7, 0x11fb000011fb1, 0x120000001239a, 0x1248000012544, 0x12f9000012ff1, 0x130000001342f, 0x1440000014647, 0x1680000016a39, 0x16a4000016a5f, 0x16a6000016a6a, 0x16a7000016abf, 0x16ac000016aca, 0x16ad000016aee, 0x16af000016af5, 0x16b0000016b37, 0x16b4000016b44, 0x16b5000016b5a, 0x16b6300016b78, 0x16b7d00016b90, 0x16e6000016e80, 0x16f0000016f4b, 0x16f4f00016f88, 0x16f8f00016fa0, 0x16fe000016fe2, 0x16fe300016fe5, 0x16ff000016ff2, 0x17000000187f8, 0x1880000018cd6, 0x18d0000018d09, 0x1aff00001aff4, 0x1aff50001affc, 0x1affd0001afff, 0x1b0000001b123, 0x1b1500001b153, 0x1b1640001b168, 0x1b1700001b2fc, 0x1bc000001bc6b, 0x1bc700001bc7d, 0x1bc800001bc89, 0x1bc900001bc9a, 0x1bc9d0001bc9f, 0x1cf000001cf2e, 0x1cf300001cf47, 0x1da000001da37, 0x1da3b0001da6d, 0x1da750001da76, 0x1da840001da85, 0x1da9b0001daa0, 0x1daa10001dab0, 0x1df000001df1f, 0x1e0000001e007, 0x1e0080001e019, 0x1e01b0001e022, 0x1e0230001e025, 0x1e0260001e02b, 0x1e1000001e12d, 0x1e1300001e13e, 0x1e1400001e14a, 0x1e14e0001e14f, 0x1e2900001e2af, 0x1e2c00001e2fa, 0x1e7e00001e7e7, 0x1e7e80001e7ec, 0x1e7ed0001e7ef, 0x1e7f00001e7ff, 0x1e8000001e8c5, 0x1e8d00001e8d7, 0x1e9220001e94c, 0x1e9500001e95a, 0x1fbf00001fbfa, 0x200000002a6e0, 0x2a7000002b739, 0x2b7400002b81e, 0x2b8200002cea2, 0x2ceb00002ebe1, 0x300000003134b, ), 'CONTEXTJ': ( 0x200c0000200e, ), 'CONTEXTO': ( 0xb7000000b8, 0x37500000376, 0x5f3000005f5, 0x6600000066a, 0x6f0000006fa, 0x30fb000030fc, ), }
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/idna/idnadata.py
idnadata.py
from __future__ import absolute_import import io import logging import zlib from contextlib import contextmanager from socket import error as SocketError from socket import timeout as SocketTimeout try: import brotli except ImportError: brotli = None from ._collections import HTTPHeaderDict from .connection import BaseSSLError, HTTPException from .exceptions import ( BodyNotHttplibCompatible, DecodeError, HTTPError, IncompleteRead, InvalidChunkLength, InvalidHeader, ProtocolError, ReadTimeoutError, ResponseNotChunked, SSLError, ) from .packages import six from .util.response import is_fp_closed, is_response_to_head log = logging.getLogger(__name__) class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = b"" self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data if not self._first_try: return self._obj.decompress(data) self._data += data try: decompressed = self._obj.decompress(data) if decompressed: self._first_try = False self._data = None return decompressed except zlib.error: self._first_try = False self._obj = zlib.decompressobj(-zlib.MAX_WBITS) try: return self.decompress(self._data) finally: self._data = None class GzipDecoderState(object): FIRST_MEMBER = 0 OTHER_MEMBERS = 1 SWALLOW_DATA = 2 class GzipDecoder(object): def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) self._state = GzipDecoderState.FIRST_MEMBER def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): ret = bytearray() if self._state == GzipDecoderState.SWALLOW_DATA or not data: return bytes(ret) while True: try: ret += self._obj.decompress(data) except zlib.error: previous_state = self._state # Ignore data after the first error self._state = GzipDecoderState.SWALLOW_DATA if previous_state == GzipDecoderState.OTHER_MEMBERS: # Allow trailing garbage acceptable in other gzip clients return bytes(ret) raise data = self._obj.unused_data if not data: return bytes(ret) self._state = GzipDecoderState.OTHER_MEMBERS self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) if brotli is not None: class BrotliDecoder(object): # Supports both 'brotlipy' and 'Brotli' packages # since they share an import name. The top branches # are for 'brotlipy' and bottom branches for 'Brotli' def __init__(self): self._obj = brotli.Decompressor() if hasattr(self._obj, "decompress"): self.decompress = self._obj.decompress else: self.decompress = self._obj.process def flush(self): if hasattr(self._obj, "flush"): return self._obj.flush() return b"" class MultiDecoder(object): """ From RFC7231: If one or more encodings have been applied to a representation, the sender that applied the encodings MUST generate a Content-Encoding header field that lists the content codings in the order in which they were applied. """ def __init__(self, modes): self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")] def flush(self): return self._decoders[0].flush() def decompress(self, data): for d in reversed(self._decoders): data = d.decompress(data) return data def _get_decoder(mode): if "," in mode: return MultiDecoder(mode) if mode == "gzip": return GzipDecoder() if brotli is not None and mode == "br": return BrotliDecoder() return DeflateDecoder() class HTTPResponse(io.IOBase): """ HTTP Response container. Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, and can hence be treated as a readable object in the context of that framework. Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param original_response: When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse` object, it's convenient to include the original for debug purposes. It's otherwise unused. :param retries: The retries contains the last :class:`~urllib3.util.retry.Retry` that was used during the request. :param enforce_content_length: Enforce content length checking. Body returned by server must match value of Content-Length header, if present. Otherwise, raise error. """ CONTENT_DECODERS = ["gzip", "deflate"] if brotli is not None: CONTENT_DECODERS += ["br"] REDIRECT_STATUSES = [301, 302, 303, 307, 308] def __init__( self, body="", headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None, msg=None, retries=None, enforce_content_length=False, request_method=None, request_url=None, auto_close=True, ): if isinstance(headers, HTTPHeaderDict): self.headers = headers else: self.headers = HTTPHeaderDict(headers) self.status = status self.version = version self.reason = reason self.strict = strict self.decode_content = decode_content self.retries = retries self.enforce_content_length = enforce_content_length self.auto_close = auto_close self._decoder = None self._body = None self._fp = None self._original_response = original_response self._fp_bytes_read = 0 self.msg = msg self._request_url = request_url if body and isinstance(body, (six.string_types, bytes)): self._body = body self._pool = pool self._connection = connection if hasattr(body, "read"): self._fp = body # Are we using the chunked-style of transfer encoding? self.chunked = False self.chunk_left = None tr_enc = self.headers.get("transfer-encoding", "").lower() # Don't incur the penalty of creating a list and then discarding it encodings = (enc.strip() for enc in tr_enc.split(",")) if "chunked" in encodings: self.chunked = True # Determine length of response self.length_remaining = self._init_length(request_method) # If requested, preload the body. if preload_content and not self._body: self._body = self.read(decode_content=decode_content) def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get("location") return False def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None def drain_conn(self): """ Read and discard any remaining HTTP response data in the response connection. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool. """ try: self.read() except (HTTPError, SocketError, BaseSSLError, HTTPException): pass @property def data(self): # For backwards-compat with earlier urllib3 0.4 and earlier. if self._body: return self._body if self._fp: return self.read(cache_content=True) @property def connection(self): return self._connection def isclosed(self): return is_fp_closed(self._fp) def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``urllib3.response.HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get("content-length") if length is not None: if self.chunked: # This Response will fail with an IncompleteRead if it can't be # received as chunked. This method falls back to attempt reading # the response before raising an exception. log.warning( "Received response with both Content-Length and " "Transfer-Encoding set. This is expressly forbidden " "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " "attempting to process response as Transfer-Encoding: " "chunked." ) return None try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = set([int(val) for val in length.split(",")]) if len(lengths) > 1: raise InvalidHeader( "Content-Length contained multiple " "unmatching values (%s)" % length ) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None # Convert status to int for comparison # In some cases, httplib returns a status of "_UNKNOWN" try: status = int(self.status) except ValueError: status = 0 # Check for responses that shouldn't include a body if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD": length = 0 return length def _init_decoder(self): """ Set-up the _decoder attribute if necessary. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get("content-encoding", "").lower() if self._decoder is None: if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif "," in content_encoding: encodings = [ e.strip() for e in content_encoding.split(",") if e.strip() in self.CONTENT_DECODERS ] if len(encodings): self._decoder = _get_decoder(content_encoding) DECODER_ERROR_CLASSES = (IOError, zlib.error) if brotli is not None: DECODER_ERROR_CLASSES += (brotli.error,) def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ if not decode_content: return data try: if self._decoder: data = self._decoder.decompress(data) except self.DECODER_ERROR_CLASSES as e: content_encoding = self.headers.get("content-encoding", "").lower() raise DecodeError( "Received response with content-encoding: %s, but " "failed to decode it." % content_encoding, e, ) if flush_decoder: data += self._flush_decoder() return data def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b"") return buf + self._decoder.flush() return b"" @contextmanager def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ clean_exit = False try: try: yield except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, "Read timed out.") except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if "read operation timed out" not in str(e): # SSL errors related to framing/MAC get wrapped and reraised here raise SSLError(e) raise ReadTimeoutError(self._pool, None, "Read timed out.") except (HTTPException, SocketError) as e: # This includes IncompleteRead. raise ProtocolError("Connection broken: %r" % e, e) # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now to ensure that the connection is # released back to the pool. if self._original_response: self._original_response.close() # Closing the response may not actually be sufficient to close # everything, so if we have a hold of the connection close that # too. if self._connection: self._connection.close() # If we hold the original response but it's closed now, we should # return the connection back to the pool. if self._original_response and self._original_response.isclosed(): self.release_conn() def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`http.client.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False fp_closed = getattr(self._fp, "closed", False) with self._error_catcher(): if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() if not fp_closed else b"" flush_decoder = True else: cache_content = False data = self._fp.read(amt) if not fp_closed else b"" if ( amt != 0 and not data ): # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True if self.enforce_content_length and self.length_remaining not in ( 0, None, ): # This is an edge case that httplib failed to cover due # to concerns of backward compatibility. We're # addressing it here to make sure IncompleteRead is # raised during streaming, so all calls with incorrect # Content-Length are caught. raise IncompleteRead(self._fp_bytes_read, self.length_remaining) if data: self._fp_bytes_read += len(data) if self.length_remaining is not None: self.length_remaining -= len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data def stream(self, amt=2 ** 16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ if self.chunked and self.supports_chunked_reads(): for line in self.read_chunked(amt, decode_content=decode_content): yield line else: while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data @classmethod def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`http.client.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if six.PY2: # Python 2.7 headers = HTTPHeaderDict.from_httplib(headers) else: headers = HTTPHeaderDict(headers.items()) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, "strict", 0) resp = ResponseCls( body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw ) return resp # Backwards-compatibility methods for http.client.HTTPResponse def getheaders(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default) # Backwards compatibility for http.cookiejar def info(self): return self.headers # Overrides from io.IOBase def close(self): if not self.closed: self._fp.close() if self._connection: self._connection.close() if not self.auto_close: io.IOBase.close(self) @property def closed(self): if not self.auto_close: return io.IOBase.closed.__get__(self) elif self._fp is None: return True elif hasattr(self._fp, "isclosed"): return self._fp.isclosed() elif hasattr(self._fp, "closed"): return self._fp.closed else: return True def fileno(self): if self._fp is None: raise IOError("HTTPResponse has no file to get a fileno from") elif hasattr(self._fp, "fileno"): return self._fp.fileno() else: raise IOError( "The file-like object this HTTPResponse is wrapped " "around has no file descriptor" ) def flush(self): if ( self._fp is not None and hasattr(self._fp, "flush") and not getattr(self._fp, "closed", False) ): return self._fp.flush() def readable(self): # This method is required for `io` module compatibility. return True def readinto(self, b): # This method is required for `io` module compatibility. temp = self.read(len(b)) if len(temp) == 0: return 0 else: b[: len(temp)] = temp return len(temp) def supports_chunked_reads(self): """ Checks if the underlying file-like object looks like a :class:`http.client.HTTPResponse` object. We do this by testing for the fp attribute. If it is present we assume it returns raw chunks as processed by read_chunked(). """ return hasattr(self._fp, "fp") def _update_chunk_length(self): # First, we'll figure out length of a chunk and then # we'll try to read it from socket. if self.chunk_left is not None: return line = self._fp.fp.readline() line = line.split(b";", 1)[0] try: self.chunk_left = int(line, 16) except ValueError: # Invalid chunked protocol response, abort. self.close() raise InvalidChunkLength(self, line) def _handle_chunk(self, amt): returned_chunk = None if amt is None: chunk = self._fp._safe_read(self.chunk_left) returned_chunk = chunk self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None elif amt < self.chunk_left: value = self._fp._safe_read(amt) self.chunk_left = self.chunk_left - amt returned_chunk = value elif amt == self.chunk_left: value = self._fp._safe_read(amt) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None returned_chunk = value else: # amt > self.chunk_left returned_chunk = self._fp._safe_read(self.chunk_left) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None return returned_chunk def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked( "Response is not chunked. " "Header 'transfer-encoding: chunked' is missing." ) if not self.supports_chunked_reads(): raise BodyNotHttplibCompatible( "Body should be http.client.HTTPResponse like. " "It should have have an fp attribute which returns raw chunks." ) with self._error_catcher(): # Don't bother reading the body of a HEAD request. if self._original_response and is_response_to_head(self._original_response): self._original_response.close() return # If a response is already read and closed # then return immediately. if self._fp.fp is None: return while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) decoded = self._decode( chunk, decode_content=decode_content, flush_decoder=False ) if decoded: yield decoded if decode_content: # On CPython and PyPy, we should never need to flush the # decoder. However, on Jython we *might* need to, so # lets defensively do it anyway. decoded = self._flush_decoder() if decoded: # Platform-specific: Jython. yield decoded # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b"\r\n": break # We read everything; close the "file". if self._original_response: self._original_response.close() def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. """ if self.retries is not None and len(self.retries.history): return self.retries.history[-1].redirect_location else: return self._request_url def __iter__(self): buffer = [] for chunk in self.stream(decode_content=True): if b"\n" in chunk: chunk = chunk.split(b"\n") yield b"".join(buffer) + chunk[0] + b"\n" for x in chunk[1:-1]: yield x + b"\n" if chunk[-1]: buffer = [chunk[-1]] else: buffer = [] else: buffer.append(chunk) if buffer: yield b"".join(buffer)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/response.py
response.py
from __future__ import absolute_import import datetime import logging import os import re import socket import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .packages import six from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection from .packages.six.moves.http_client import HTTPException # noqa: F401 from .util.proxy import create_proxy_ssl_context try: # Compiled with SSL? import ssl BaseSSLError = ssl.SSLError except (ImportError, AttributeError): # Platform-specific: No SSL. ssl = None class BaseSSLError(BaseException): pass try: # Python 3: not a no-op, we're adding this to the namespace so it can be imported. ConnectionError = ConnectionError except NameError: # Python 2 class ConnectionError(Exception): pass try: # Python 3: # Not a no-op, we're adding this to the namespace so it can be imported. BrokenPipeError = BrokenPipeError except NameError: # Python 2: class BrokenPipeError(Exception): pass from ._collections import HTTPHeaderDict # noqa (historical, removed in v2) from ._version import __version__ from .exceptions import ( ConnectTimeoutError, NewConnectionError, SubjectAltNameWarning, SystemTimeWarning, ) from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection from .util.ssl_ import ( assert_fingerprint, create_urllib3_context, is_ipaddress, resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, ) from .util.ssl_match_hostname import CertificateError, match_hostname log = logging.getLogger(__name__) port_by_scheme = {"http": 80, "https": 443} # When it comes time to update this value as a part of regular maintenance # (ie test_recent_date is failing) update it to ~6 months before the current date. RECENT_DATE = datetime.date(2020, 7, 1) _CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]") class HTTPConnection(_HTTPConnection, object): """ Based on :class:`http.client.HTTPConnection` but provides an extra constructor backwards-compatibility layer between older and newer Pythons. Additional keyword parameters are used to configure attributes of the connection. Accepted parameters include: - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool` - ``source_address``: Set the source address for the current connection. - ``socket_options``: Set specific options on the underlying socket. If not specified, then defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy. For example, if you wish to enable TCP Keep Alive in addition to the defaults, you might pass: .. code-block:: python HTTPConnection.default_socket_options + [ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), ] Or you may want to disable the defaults by passing an empty list (e.g., ``[]``). """ default_port = port_by_scheme["http"] #: Disable Nagle's algorithm by default. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]`` default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] #: Whether this connection verifies the host's certificate. is_verified = False #: Whether this proxy connection (if used) verifies the proxy host's #: certificate. proxy_is_verified = None def __init__(self, *args, **kw): if not six.PY2: kw.pop("strict", None) # Pre-set source_address. self.source_address = kw.get("source_address") #: The socket options provided by the user. If no options are #: provided, we use the default options. self.socket_options = kw.pop("socket_options", self.default_socket_options) # Proxy options provided by the user. self.proxy = kw.pop("proxy", None) self.proxy_config = kw.pop("proxy_config", None) _HTTPConnection.__init__(self, *args, **kw) @property def host(self): """ Getter method to remove any trailing dots that indicate the hostname is an FQDN. In general, SSL certificates don't include the trailing dot indicating a fully-qualified domain name, and thus, they don't validate properly when checked against a domain name that includes the dot. In addition, some servers may not expect to receive the trailing dot when provided. However, the hostname with trailing dot is critical to DNS resolution; doing a lookup with the trailing dot will properly only resolve the appropriate FQDN, whereas a lookup without a trailing dot will search the system's search domain list. Thus, it's important to keep the original host around for use only in those cases where it's appropriate (i.e., when doing DNS lookup to establish the actual TCP connection across which we're going to send HTTP requests). """ return self._dns_host.rstrip(".") @host.setter def host(self, value): """ Setter for the `host` property. We assume that only urllib3 uses the _dns_host attribute; httplib itself only uses `host`, and it seems reasonable that other libraries follow suit. """ self._dns_host = value def _new_conn(self): """Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ extra_kw = {} if self.source_address: extra_kw["source_address"] = self.source_address if self.socket_options: extra_kw["socket_options"] = self.socket_options try: conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) except SocketError as e: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) return conn def _is_using_tunnel(self): # Google App Engine's httplib does not define _tunnel_host return getattr(self, "_tunnel_host", None) def _prepare_conn(self, conn): self.sock = conn if self._is_using_tunnel(): # TODO: Fix tunnel so it doesn't depend on self.sock state. self._tunnel() # Mark this connection as not reusable self.auto_open = 0 def connect(self): conn = self._new_conn() self._prepare_conn(conn) def putrequest(self, method, url, *args, **kwargs): """ """ # Empty docstring because the indentation of CPython's implementation # is broken but we don't want this method in our documentation. match = _CONTAINS_CONTROL_CHAR_RE.search(method) if match: raise ValueError( "Method cannot contain non-token characters %r (found at least %r)" % (method, match.group()) ) return _HTTPConnection.putrequest(self, method, url, *args, **kwargs) def putheader(self, header, *values): """ """ if not any(isinstance(v, str) and v == SKIP_HEADER for v in values): _HTTPConnection.putheader(self, header, *values) elif six.ensure_str(header.lower()) not in SKIPPABLE_HEADERS: raise ValueError( "urllib3.util.SKIP_HEADER only supports '%s'" % ("', '".join(map(str.title, sorted(SKIPPABLE_HEADERS))),) ) def request(self, method, url, body=None, headers=None): if headers is None: headers = {} else: # Avoid modifying the headers passed into .request() headers = headers.copy() if "user-agent" not in (six.ensure_str(k.lower()) for k in headers): headers["User-Agent"] = _get_default_user_agent() super(HTTPConnection, self).request(method, url, body=body, headers=headers) def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = headers or {} header_keys = set([six.ensure_str(k.lower()) for k in headers]) skip_accept_encoding = "accept-encoding" in header_keys skip_host = "host" in header_keys self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) if "user-agent" not in header_keys: self.putheader("User-Agent", _get_default_user_agent()) for header, value in headers.items(): self.putheader(header, value) if "transfer-encoding" not in header_keys: self.putheader("Transfer-Encoding", "chunked") self.endheaders() if body is not None: stringish_types = six.string_types + (bytes,) if isinstance(body, stringish_types): body = (body,) for chunk in body: if not chunk: continue if not isinstance(chunk, bytes): chunk = chunk.encode("utf8") len_str = hex(len(chunk))[2:] to_send = bytearray(len_str.encode()) to_send += b"\r\n" to_send += chunk to_send += b"\r\n" self.send(to_send) # After the if clause, to always have a closed body self.send(b"0\r\n\r\n") class HTTPSConnection(HTTPConnection): """ Many of the parameters to this constructor are passed to the underlying SSL socket by means of :py:func:`urllib3.util.ssl_wrap_socket`. """ default_port = port_by_scheme["https"] cert_reqs = None ca_certs = None ca_cert_dir = None ca_cert_data = None ssl_version = None assert_fingerprint = None tls_in_tls_required = False def __init__( self, host, port=None, key_file=None, cert_file=None, key_password=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, ssl_context=None, server_hostname=None, **kw ): HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw) self.key_file = key_file self.cert_file = cert_file self.key_password = key_password self.ssl_context = ssl_context self.server_hostname = server_hostname # Required property for Google AppEngine 1.9.0 which otherwise causes # HTTPS requests to go out as HTTP. (See Issue #356) self._protocol = "https" def set_cert( self, key_file=None, cert_file=None, cert_reqs=None, key_password=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, ca_cert_data=None, ): """ This method should only be called once, before the connection is used. """ # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also # have an SSLContext object in which case we'll use its verify_mode. if cert_reqs is None: if self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode else: cert_reqs = resolve_cert_reqs(None) self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.key_password = key_password self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) self.ca_cert_data = ca_cert_data def connect(self): # Add certificate verification conn = self._new_conn() hostname = self.host tls_in_tls = False if self._is_using_tunnel(): if self.tls_in_tls_required: conn = self._connect_tls_proxy(hostname, conn) tls_in_tls = True self.sock = conn # Calls self._set_hostport(), so self.host is # self._tunnel_host below. self._tunnel() # Mark this connection as not reusable self.auto_open = 0 # Override the host with the one we're requesting data from. hostname = self._tunnel_host server_hostname = hostname if self.server_hostname is not None: server_hostname = self.server_hostname is_time_off = datetime.date.today() < RECENT_DATE if is_time_off: warnings.warn( ( "System time is way off (before {0}). This will probably " "lead to SSL verification errors" ).format(RECENT_DATE), SystemTimeWarning, ) # Wrap socket using verification with the root certs in # trusted_root_certs default_ssl_context = False if self.ssl_context is None: default_ssl_context = True self.ssl_context = create_urllib3_context( ssl_version=resolve_ssl_version(self.ssl_version), cert_reqs=resolve_cert_reqs(self.cert_reqs), ) context = self.ssl_context context.verify_mode = resolve_cert_reqs(self.cert_reqs) # Try to load OS default certs if none are given. # Works well on Windows (requires Python3.4+) if ( not self.ca_certs and not self.ca_cert_dir and not self.ca_cert_data and default_ssl_context and hasattr(context, "load_default_certs") ): context.load_default_certs() self.sock = ssl_wrap_socket( sock=conn, keyfile=self.key_file, certfile=self.cert_file, key_password=self.key_password, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, ca_cert_data=self.ca_cert_data, server_hostname=server_hostname, ssl_context=context, tls_in_tls=tls_in_tls, ) # If we're using all defaults and the connection # is TLSv1 or TLSv1.1 we throw a DeprecationWarning # for the host. if ( default_ssl_context and self.ssl_version is None and hasattr(self.sock, "version") and self.sock.version() in {"TLSv1", "TLSv1.1"} ): warnings.warn( "Negotiating TLSv1/TLSv1.1 by default is deprecated " "and will be disabled in urllib3 v2.0.0. Connecting to " "'%s' with '%s' can be enabled by explicitly opting-in " "with 'ssl_version'" % (self.host, self.sock.version()), DeprecationWarning, ) if self.assert_fingerprint: assert_fingerprint( self.sock.getpeercert(binary_form=True), self.assert_fingerprint ) elif ( context.verify_mode != ssl.CERT_NONE and not getattr(context, "check_hostname", False) and self.assert_hostname is not False ): # While urllib3 attempts to always turn off hostname matching from # the TLS library, this cannot always be done. So we check whether # the TLS Library still thinks it's matching hostnames. cert = self.sock.getpeercert() if not cert.get("subjectAltName", ()): warnings.warn( ( "Certificate for {0} has no `subjectAltName`, falling back to check for a " "`commonName` for now. This feature is being removed by major browsers and " "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 " "for details.)".format(hostname) ), SubjectAltNameWarning, ) _match_hostname(cert, self.assert_hostname or server_hostname) self.is_verified = ( context.verify_mode == ssl.CERT_REQUIRED or self.assert_fingerprint is not None ) def _connect_tls_proxy(self, hostname, conn): """ Establish a TLS connection to the proxy using the provided SSL context. """ proxy_config = self.proxy_config ssl_context = proxy_config.ssl_context if ssl_context: # If the user provided a proxy context, we assume CA and client # certificates have already been set return ssl_wrap_socket( sock=conn, server_hostname=hostname, ssl_context=ssl_context, ) ssl_context = create_proxy_ssl_context( self.ssl_version, self.cert_reqs, self.ca_certs, self.ca_cert_dir, self.ca_cert_data, ) # If no cert was provided, use only the default options for server # certificate validation socket = ssl_wrap_socket( sock=conn, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, ca_cert_data=self.ca_cert_data, server_hostname=hostname, ssl_context=ssl_context, ) if ssl_context.verify_mode != ssl.CERT_NONE and not getattr( ssl_context, "check_hostname", False ): # While urllib3 attempts to always turn off hostname matching from # the TLS library, this cannot always be done. So we check whether # the TLS Library still thinks it's matching hostnames. cert = socket.getpeercert() if not cert.get("subjectAltName", ()): warnings.warn( ( "Certificate for {0} has no `subjectAltName`, falling back to check for a " "`commonName` for now. This feature is being removed by major browsers and " "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 " "for details.)".format(hostname) ), SubjectAltNameWarning, ) _match_hostname(cert, hostname) self.proxy_is_verified = ssl_context.verify_mode == ssl.CERT_REQUIRED return socket def _match_hostname(cert, asserted_hostname): # Our upstream implementation of ssl.match_hostname() # only applies this normalization to IP addresses so it doesn't # match DNS SANs so we do the same thing! stripped_hostname = asserted_hostname.strip("u[]") if is_ipaddress(stripped_hostname): asserted_hostname = stripped_hostname try: match_hostname(cert, asserted_hostname) except CertificateError as e: log.warning( "Certificate did not match expected hostname: %s. Certificate: %s", asserted_hostname, cert, ) # Add cert to exception and reraise so client code can inspect # the cert when catching the exception, if they want to e._peer_cert = cert raise def _get_default_user_agent(): return "python-urllib3/%s" % __version__ class DummyConnection(object): """Used to detect a failed ConnectionCls import.""" pass if not ssl: HTTPSConnection = DummyConnection # noqa: F811 VerifiedHTTPSConnection = HTTPSConnection
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/connection.py
connection.py
from __future__ import absolute_import import binascii import codecs import os from io import BytesIO from .fields import RequestField from .packages import six from .packages.six import b writer = codecs.lookup("utf-8")[3] def choose_boundary(): """ Our embarrassingly-simple replacement for mimetools.choose_boundary. """ boundary = binascii.hexlify(os.urandom(16)) if not six.PY2: boundary = boundary.decode("ascii") return boundary def iter_field_objects(fields): """ Iterate over fields. Supports list of (k, v) tuples and dicts, and lists of :class:`~urllib3.fields.RequestField`. """ if isinstance(fields, dict): i = six.iteritems(fields) else: i = iter(fields) for field in i: if isinstance(field, RequestField): yield field else: yield RequestField.from_tuples(*field) def iter_fields(fields): """ .. deprecated:: 1.6 Iterate over fields. The addition of :class:`~urllib3.fields.RequestField` makes this function obsolete. Instead, use :func:`iter_field_objects`, which returns :class:`~urllib3.fields.RequestField` objects. Supports list of (k, v) tuples and dicts. """ if isinstance(fields, dict): return ((k, v) for k, v in six.iteritems(fields)) return ((k, v) for k, v in fields) def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`urllib3.filepost.choose_boundary`. """ body = BytesIO() if boundary is None: boundary = choose_boundary() for field in iter_field_objects(fields): body.write(b("--%s\r\n" % (boundary))) writer(body).write(field.render_headers()) data = field.data if isinstance(data, int): data = str(data) # Backwards compatibility if isinstance(data, six.text_type): writer(body).write(data) else: body.write(data) body.write(b"\r\n") body.write(b("--%s--\r\n" % (boundary))) content_type = str("multipart/form-data; boundary=%s" % boundary) return body.getvalue(), content_type
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/filepost.py
filepost.py
from __future__ import absolute_import import errno import logging import re import socket import sys import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .connection import ( BaseSSLError, BrokenPipeError, DummyConnection, HTTPConnection, HTTPException, HTTPSConnection, VerifiedHTTPSConnection, port_by_scheme, ) from .exceptions import ( ClosedPoolError, EmptyPoolError, HeaderParsingError, HostChangedError, InsecureRequestWarning, LocationValueError, MaxRetryError, NewConnectionError, ProtocolError, ProxyError, ReadTimeoutError, SSLError, TimeoutError, ) from .packages import six from .packages.six.moves import queue from .request import RequestMethods from .response import HTTPResponse from .util.connection import is_connection_dropped from .util.proxy import connection_requires_http_tunnel from .util.queue import LifoQueue from .util.request import set_file_position from .util.response import assert_header_parsing from .util.retry import Retry from .util.ssl_match_hostname import CertificateError from .util.timeout import Timeout from .util.url import Url, _encode_target from .util.url import _normalize_host as normalize_host from .util.url import get_host, parse_url xrange = six.moves.xrange log = logging.getLogger(__name__) _Default = object() # Pool objects class ConnectionPool(object): """ Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. .. note:: ConnectionPool.urlopen() does not normalize or percent-encode target URIs which is useful if your target server doesn't support percent-encoded target URIs. """ scheme = None QueueCls = LifoQueue def __init__(self, host, port=None): if not host: raise LocationValueError("No host specified.") self.host = _normalize_host(host, scheme=self.scheme) self._proxy_host = host.lower() self.port = port def __str__(self): return "%s(host=%r, port=%r)" % (type(self).__name__, self.host, self.port) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() # Return False to re-raise any potential exceptions return False def close(self): """ Close all pooled connections and disable the pool. """ pass # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252 _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK} class HTTPConnectionPool(ConnectionPool, RequestMethods): """ Thread-safe connection pool for one host. :param host: Host used for this HTTP Connection (e.g. "localhost"), passed into :class:`http.client.HTTPConnection`. :param port: Port used for this HTTP Connection (None is equivalent to 80), passed into :class:`http.client.HTTPConnection`. :param strict: Causes BadStatusLine to be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1 status line, passed into :class:`http.client.HTTPConnection`. .. note:: Only works in Python 2. This parameter is ignored in Python 3. :param timeout: Socket timeout in seconds for each individual connection. This can be a float or integer, which sets the timeout for the HTTP request, or an instance of :class:`urllib3.util.Timeout` which gives you more fine-grained control over request timeouts. After the constructor has been parsed, this is always a `urllib3.util.Timeout` object. :param maxsize: Number of connections to save that can be reused. More than 1 is useful in multithreaded situations. If ``block`` is set to False, more connections will be created but they will not be saved once they've been used. :param block: If set to True, no more than ``maxsize`` connections will be used at a time. When no free connections are available, the call will block until a connection has been released. This is a useful side effect for particular multithreaded situations where one does not want to use more than maxsize connections per host to prevent flooding. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param retries: Retry configuration to use by default with requests in this pool. :param _proxy: Parsed proxy URL, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param _proxy_headers: A dictionary with proxy headers, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param \\**conn_kw: Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, :class:`urllib3.connection.HTTPSConnection` instances. """ scheme = "http" ConnectionCls = HTTPConnection ResponseCls = HTTPResponse def __init__( self, host, port=None, strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, _proxy_config=None, **conn_kw ): ConnectionPool.__init__(self, host, port) RequestMethods.__init__(self, headers) self.strict = strict if not isinstance(timeout, Timeout): timeout = Timeout.from_float(timeout) if retries is None: retries = Retry.DEFAULT self.timeout = timeout self.retries = retries self.pool = self.QueueCls(maxsize) self.block = block self.proxy = _proxy self.proxy_headers = _proxy_headers or {} self.proxy_config = _proxy_config # Fill the queue up so that doing get() on it will block properly for _ in xrange(maxsize): self.pool.put(None) # These are mostly for testing and debugging purposes. self.num_connections = 0 self.num_requests = 0 self.conn_kw = conn_kw if self.proxy: # Enable Nagle's algorithm for proxies, to avoid packet fragmentation. # We cannot know if the user has added default socket options, so we cannot replace the # list. self.conn_kw.setdefault("socket_options", []) self.conn_kw["proxy"] = self.proxy self.conn_kw["proxy_config"] = self.proxy_config def _new_conn(self): """ Return a fresh :class:`HTTPConnection`. """ self.num_connections += 1 log.debug( "Starting new HTTP connection (%d): %s:%s", self.num_connections, self.host, self.port or "80", ) conn = self.ConnectionCls( host=self.host, port=self.port, timeout=self.timeout.connect_timeout, strict=self.strict, **self.conn_kw ) return conn def _get_conn(self, timeout=None): """ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. """ conn = None try: conn = self.pool.get(block=self.block, timeout=timeout) except AttributeError: # self.pool is None raise ClosedPoolError(self, "Pool is closed.") except queue.Empty: if self.block: raise EmptyPoolError( self, "Pool reached maximum size and no more connections are allowed.", ) pass # Oh well, we'll create a new connection then # If this is a persistent connection, check if it got disconnected if conn and is_connection_dropped(conn): log.debug("Resetting dropped connection: %s", self.host) conn.close() if getattr(conn, "auto_open", 1) == 0: # This is a proxied connection that has been mutated by # http.client._tunnel() and cannot be reused (since it would # attempt to bypass the proxy) conn = None return conn or self._new_conn() def _put_conn(self, conn): """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded. """ try: self.pool.put(conn, block=False) return # Everything is dandy, done. except AttributeError: # self.pool is None. pass except queue.Full: # This should never happen if self.block == True log.warning( "Connection pool is full, discarding connection: %s. Connection pool size: %s", self.host, self.pool.qsize(), ) # Connection never got put back into the pool, close it. if conn: conn.close() def _validate_conn(self, conn): """ Called right before a request is made, after the socket is created. """ pass def _prepare_proxy(self, conn): # Nothing to do for HTTP connections. pass def _get_timeout(self, timeout): """Helper that always returns a :class:`urllib3.util.Timeout`""" if timeout is _Default: return self.timeout.clone() if isinstance(timeout, Timeout): return timeout.clone() else: # User passed us an int/float. This is for backwards compatibility, # can be removed later return Timeout.from_float(timeout) def _raise_timeout(self, err, url, timeout_value): """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) # See the above comment about EAGAIN in Python 3. In Python 2 we have # to specifically catch it and throw the timeout error if hasattr(err, "errno") and err.errno in _blocking_errnos: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) # Catch possible read timeouts thrown as SSL errors. If not the # case, rethrow the original. We need to do this because of: # http://bugs.python.org/issue10272 if "timed out" in str(err) or "did not complete (read)" in str( err ): # Python < 2.7.4 raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) def _make_request( self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw ): """ Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts. """ self.num_requests += 1 timeout_obj = self._get_timeout(timeout) timeout_obj.start_connect() conn.timeout = timeout_obj.connect_timeout # Trigger any extra validation we need to do. try: self._validate_conn(conn) except (SocketTimeout, BaseSSLError) as e: # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) raise # conn.request() calls http.client.*.request, not the method in # urllib3.request. It also calls makefile (recv) on the socket. try: if chunked: conn.request_chunked(method, url, **httplib_request_kw) else: conn.request(method, url, **httplib_request_kw) # We are swallowing BrokenPipeError (errno.EPIPE) since the server is # legitimately able to close the connection after sending a valid response. # With this behaviour, the received response is still readable. except BrokenPipeError: # Python 3 pass except IOError as e: # Python 2 and macOS/Linux # EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE is needed on macOS # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/ if e.errno not in { errno.EPIPE, errno.ESHUTDOWN, errno.EPROTOTYPE, }: raise # Reset the timeout for the recv() on the socket read_timeout = timeout_obj.read_timeout # App Engine doesn't have a sock attr if getattr(conn, "sock", None): # In Python 3 socket.py will catch EAGAIN and return None when you # try and read into the file pointer created by http.client, which # instead raises a BadStatusLine exception. Instead of catching # the exception and assuming all BadStatusLine exceptions are read # timeouts, check for a zero timeout before making the request. if read_timeout == 0: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % read_timeout ) if read_timeout is Timeout.DEFAULT_TIMEOUT: conn.sock.settimeout(socket.getdefaulttimeout()) else: # None or a value conn.sock.settimeout(read_timeout) # Receive the response from the server try: try: # Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) except TypeError: # Python 3 try: httplib_response = conn.getresponse() except BaseException as e: # Remove the TypeError from the exception chain in # Python 3 (including for exceptions like SystemExit). # Otherwise it looks like a bug in the code. six.raise_from(e, None) except (SocketTimeout, BaseSSLError, SocketError) as e: self._raise_timeout(err=e, url=url, timeout_value=read_timeout) raise # AppEngine doesn't have a version attr. http_version = getattr(conn, "_http_vsn_str", "HTTP/?") log.debug( '%s://%s:%s "%s %s %s" %s %s', self.scheme, self.host, self.port, method, url, http_version, httplib_response.status, httplib_response.length, ) try: assert_header_parsing(httplib_response.msg) except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3 log.warning( "Failed to parse headers (url=%s): %s", self._absolute_url(url), hpe, exc_info=True, ) return httplib_response def _absolute_url(self, path): return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url def close(self): """ Close all pooled connections and disable the pool. """ if self.pool is None: return # Disable access to the pool old_pool, self.pool = self.pool, None try: while True: conn = old_pool.get(block=False) if conn: conn.close() except queue.Empty: pass # Done. def is_same_host(self, url): """ Check if the given ``url`` is a member of the same host as this connection pool. """ if url.startswith("/"): return True # TODO: Add optional support for socket.gethostbyname checking. scheme, host, port = get_host(url) if host is not None: host = _normalize_host(host, scheme=scheme) # Use explicit default port for comparison when none is given if self.port and not port: port = port_by_scheme.get(scheme) elif not self.port and port == port_by_scheme.get(scheme): port = None return (scheme, host, port) == (self.scheme, self.host, self.port) def urlopen( self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw ): """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param url: The URL to perform the request on. :param body: Data to send in the request body, either :class:`str`, :class:`bytes`, an iterable of :class:`str`/:class:`bytes`, or a file-like object. :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When ``False``, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param int body_pos: Position to seek to in file-like body in the event of a retry or redirect. Typically this won't need to be set because urllib3 will auto-populate the value when needed. :param \\**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` """ parsed_url = parse_url(url) destination_scheme = parsed_url.scheme if headers is None: headers = self.headers if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if release_conn is None: release_conn = response_kw.get("preload_content", True) # Check host if assert_same_host and not self.is_same_host(url): raise HostChangedError(self, url, retries) # Ensure that the URL we're connecting to is properly encoded if url.startswith("/"): url = six.ensure_str(_encode_target(url)) else: url = six.ensure_str(parsed_url.url) conn = None # Track whether `conn` needs to be released before # returning/raising/recursing. Update this variable if necessary, and # leave `release_conn` constant throughout the function. That way, if # the function recurses, the original value of `release_conn` will be # passed down into the recursive call, and its value will be respected. # # See issue #651 [1] for details. # # [1] <https://github.com/urllib3/urllib3/issues/651> release_this_conn = release_conn http_tunnel_required = connection_requires_http_tunnel( self.proxy, self.proxy_config, destination_scheme ) # Merge the proxy headers. Only done when not using HTTP CONNECT. We # have to copy the headers dict so we can safely change it without those # changes being reflected in anyone else's copy. if not http_tunnel_required: headers = headers.copy() headers.update(self.proxy_headers) # Must keep the exception bound to a separate variable or else Python 3 # complains about UnboundLocalError. err = None # Keep track of whether we cleanly exited the except block. This # ensures we do proper cleanup in finally. clean_exit = False # Rewind body position, if needed. Record current position # for future rewinds in the event of a redirect/retry. body_pos = set_file_position(body, body_pos) try: # Request a connection from the queue. timeout_obj = self._get_timeout(timeout) conn = self._get_conn(timeout=pool_timeout) conn.timeout = timeout_obj.connect_timeout is_new_proxy_conn = self.proxy is not None and not getattr( conn, "sock", None ) if is_new_proxy_conn and http_tunnel_required: self._prepare_proxy(conn) # Make the request on the httplib connection object. httplib_response = self._make_request( conn, method, url, timeout=timeout_obj, body=body, headers=headers, chunked=chunked, ) # If we're going to release the connection in ``finally:``, then # the response doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = conn if not release_conn else None # Pass method to Response for length checking response_kw["request_method"] = method # Import httplib's response into our own wrapper object response = self.ResponseCls.from_httplib( httplib_response, pool=self, connection=response_conn, retries=retries, **response_kw ) # Everything went great! clean_exit = True except EmptyPoolError: # Didn't get a connection from the pool, no need to clean up clean_exit = True release_this_conn = False raise except ( TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError, CertificateError, ) as e: # Discard the connection for these exceptions. It will be # replaced during the next _get_conn() call. clean_exit = False def _is_ssl_error_message_from_http_proxy(ssl_error): # We're trying to detect the message 'WRONG_VERSION_NUMBER' but # SSLErrors are kinda all over the place when it comes to the message, # so we try to cover our bases here! message = " ".join(re.split("[^a-z]", str(ssl_error).lower())) return ( "wrong version number" in message or "unknown protocol" in message ) # Try to detect a common user error with proxies which is to # set an HTTP proxy to be HTTPS when it should be 'http://' # (ie {'http': 'http://proxy', 'https': 'https://proxy'}) # Instead we add a nice error message and point to a URL. if ( isinstance(e, BaseSSLError) and self.proxy and _is_ssl_error_message_from_http_proxy(e) ): e = ProxyError( "Your proxy appears to only use HTTP and not HTTPS, " "try changing your proxy URL to be HTTP. See: " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#https-proxy-error-http-proxy", SSLError(e), ) elif isinstance(e, (BaseSSLError, CertificateError)): e = SSLError(e) elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy: e = ProxyError("Cannot connect to proxy.", e) elif isinstance(e, (SocketError, HTTPException)): e = ProtocolError("Connection aborted.", e) retries = retries.increment( method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] ) retries.sleep() # Keep track of the error for the retry warning. err = e finally: if not clean_exit: # We hit some kind of exception, handled or otherwise. We need # to throw the connection away unless explicitly told not to. # Close the connection, set the variable to None, and make sure # we put the None back in the pool to avoid leaking it. conn = conn and conn.close() release_this_conn = True if release_this_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. self._put_conn(conn) if not conn: # Try again log.warning( "Retrying (%r) after connection broken by '%r': %s", retries, err, url ) return self.urlopen( method, url, body, headers, retries, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, **response_kw ) # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: if response.status == 303: method = "GET" try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_redirect: response.drain_conn() raise return response response.drain_conn() retries.sleep_for_retry(response) log.debug("Redirecting %s -> %s", url, redirect_location) return self.urlopen( method, redirect_location, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, **response_kw ) # Check if we should retry the HTTP response. has_retry_after = bool(response.getheader("Retry-After")) if retries.is_retry(method, response.status, has_retry_after): try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_status: response.drain_conn() raise return response response.drain_conn() retries.sleep(response) log.debug("Retry: %s", url) return self.urlopen( method, url, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, **response_kw ) return response class HTTPSConnectionPool(HTTPConnectionPool): """ Same as :class:`.HTTPConnectionPool`, but HTTPS. :class:`.HTTPSConnection` uses one of ``assert_fingerprint``, ``assert_hostname`` and ``host`` in this order to verify connections. If ``assert_hostname`` is False, no verification is done. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl` is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket into an SSL socket. """ scheme = "https" ConnectionCls = HTTPSConnection def __init__( self, host, port=None, strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, key_file=None, cert_file=None, cert_reqs=None, key_password=None, ca_certs=None, ssl_version=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, **conn_kw ): HTTPConnectionPool.__init__( self, host, port, strict, timeout, maxsize, block, headers, retries, _proxy, _proxy_headers, **conn_kw ) self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.key_password = key_password self.ca_certs = ca_certs self.ca_cert_dir = ca_cert_dir self.ssl_version = ssl_version self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint def _prepare_conn(self, conn): """ Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used. """ if isinstance(conn, VerifiedHTTPSConnection): conn.set_cert( key_file=self.key_file, key_password=self.key_password, cert_file=self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, assert_hostname=self.assert_hostname, assert_fingerprint=self.assert_fingerprint, ) conn.ssl_version = self.ssl_version return conn def _prepare_proxy(self, conn): """ Establishes a tunnel connection through HTTP CONNECT. Tunnel connection is established early because otherwise httplib would improperly set Host: header to proxy's IP:port. """ conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers) if self.proxy.scheme == "https": conn.tls_in_tls_required = True conn.connect() def _new_conn(self): """ Return a fresh :class:`http.client.HTTPSConnection`. """ self.num_connections += 1 log.debug( "Starting new HTTPS connection (%d): %s:%s", self.num_connections, self.host, self.port or "443", ) if not self.ConnectionCls or self.ConnectionCls is DummyConnection: raise SSLError( "Can't connect to HTTPS URL because the SSL module is not available." ) actual_host = self.host actual_port = self.port if self.proxy is not None: actual_host = self.proxy.host actual_port = self.proxy.port conn = self.ConnectionCls( host=actual_host, port=actual_port, timeout=self.timeout.connect_timeout, strict=self.strict, cert_file=self.cert_file, key_file=self.key_file, key_password=self.key_password, **self.conn_kw ) return self._prepare_conn(conn) def _validate_conn(self, conn): """ Called right before a request is made, after the socket is created. """ super(HTTPSConnectionPool, self)._validate_conn(conn) # Force connect early to allow us to validate the connection. if not getattr(conn, "sock", None): # AppEngine might not have `.sock` conn.connect() if not conn.is_verified: warnings.warn( ( "Unverified HTTPS request is being made to host '%s'. " "Adding certificate verification is strongly advised. See: " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#ssl-warnings" % conn.host ), InsecureRequestWarning, ) if getattr(conn, "proxy_is_verified", None) is False: warnings.warn( ( "Unverified HTTPS connection done to an HTTPS proxy. " "Adding certificate verification is strongly advised. See: " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#ssl-warnings" ), InsecureRequestWarning, ) def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \\**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example:: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') """ scheme, host, port = get_host(url) port = port or port_by_scheme.get(scheme, 80) if scheme == "https": return HTTPSConnectionPool(host, port=port, **kw) else: return HTTPConnectionPool(host, port=port, **kw) def _normalize_host(host, scheme): """ Normalize hosts for comparisons and use with sockets. """ host = normalize_host(host, scheme) # httplib doesn't like it when we include brackets in IPv6 addresses # Specifically, if we include brackets but also pass the port then # httplib crazily doubles up the square brackets on the Host header. # Instead, we need to make sure we never pass ``None`` as the port. # However, for backward compatibility reasons we can't actually # *assert* that. See http://bugs.python.org/issue28539 if host.startswith("[") and host.endswith("]"): host = host[1:-1] return host
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/connectionpool.py
connectionpool.py
from __future__ import absolute_import import collections import functools import logging from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, ProxySchemeUnsupported, URLSchemeUnknown, ) from .packages import six from .packages.six.moves.urllib.parse import urljoin from .request import RequestMethods from .util.proxy import connection_requires_http_tunnel from .util.retry import Retry from .util.url import parse_url __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ca_cert_dir", "ssl_context", "key_password", ) # All known keyword arguments that could be provided to the pool manager, its # pools, or the underlying connections. This is used to construct a pool key. _key_fields = ( "key_scheme", # str "key_host", # str "key_port", # int "key_timeout", # int or float or Timeout "key_retries", # int or Retry "key_strict", # bool "key_block", # bool "key_source_address", # str "key_key_file", # str "key_key_password", # str "key_cert_file", # str "key_cert_reqs", # str "key_ca_certs", # str "key_ssl_version", # str "key_ca_cert_dir", # str "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext "key_maxsize", # int "key_headers", # dict "key__proxy", # parsed proxy url "key__proxy_headers", # dict "key__proxy_config", # class "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples "key__socks_options", # dict "key_assert_hostname", # bool or string "key_assert_fingerprint", # str "key_server_hostname", # str ) #: The namedtuple class used to construct keys for the connection pool. #: All custom key schemes should include the fields in this key at a minimum. PoolKey = collections.namedtuple("PoolKey", _key_fields) _proxy_config_fields = ("ssl_context", "use_forwarding_for_https") ProxyConfig = collections.namedtuple("ProxyConfig", _proxy_config_fields) def _default_key_normalizer(key_class, request_context): """ Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param key_class: The class to use when constructing the key. This should be a namedtuple with the ``scheme`` and ``host`` keys at a minimum. :type key_class: namedtuple :param request_context: A dictionary-like object that contain the context for a request. :type request_context: dict :return: A namedtuple that can be used as a connection pool key. :rtype: PoolKey """ # Since we mutate the dictionary, make a copy first context = request_context.copy() context["scheme"] = context["scheme"].lower() context["host"] = context["host"].lower() # These are both dictionaries and need to be transformed into frozensets for key in ("headers", "_proxy_headers", "_socks_options"): if key in context and context[key] is not None: context[key] = frozenset(context[key].items()) # The socket_options key may be a list and needs to be transformed into a # tuple. socket_opts = context.get("socket_options") if socket_opts is not None: context["socket_options"] = tuple(socket_opts) # Map the kwargs to the names in the namedtuple - this is necessary since # namedtuples can't have fields starting with '_'. for key in list(context.keys()): context["key_" + key] = context.pop(key) # Default to ``None`` for keys missing from the context for field in key_class._fields: if field not in context: context[field] = None return key_class(**context) #: A dictionary that maps a scheme to a callable that creates a pool key. #: This can be used to alter the way pool keys are constructed, if desired. #: Each PoolManager makes a copy of this dictionary so they can be configured #: globally here, or individually on the instance. key_fn_by_scheme = { "http": functools.partial(_default_key_normalizer, PoolKey), "https": functools.partial(_default_key_normalizer, PoolKey), } pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} class PoolManager(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param \\**connection_pool_kw: Additional parameters are used to create fresh :class:`urllib3.connectionpool.ConnectionPool` instances. Example:: >>> manager = PoolManager(num_pools=2) >>> r = manager.request('GET', 'http://google.com/') >>> r = manager.request('GET', 'http://google.com/mail') >>> r = manager.request('GET', 'http://yahoo.com/') >>> len(manager.pools) 2 """ proxy = None proxy_config = None def __init__(self, num_pools=10, headers=None, **connection_pool_kw): RequestMethods.__init__(self, headers) self.connection_pool_kw = connection_pool_kw self.pools = RecentlyUsedContainer(num_pools, dispose_func=lambda p: p.close()) # Locally set the pool classes and keys so other PoolManagers can # override them. self.pool_classes_by_scheme = pool_classes_by_scheme self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.clear() # Return False to re-raise any potential exceptions return False def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context["scheme"] = scheme or "http" if not port: port = port_by_scheme.get(request_context["scheme"].lower(), 80) request_context["port"] = port request_context["host"] = host return self.connection_from_context(request_context) def connection_from_context(self, request_context): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. """ scheme = request_context["scheme"].lower() pool_key_constructor = self.key_fn_by_scheme.get(scheme) if not pool_key_constructor: raise URLSchemeUnknown(scheme) pool_key = pool_key_constructor(request_context) return self.connection_from_pool_key(pool_key, request_context=request_context) def connection_from_pool_key(self, pool_key, request_context=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields. """ with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type scheme = request_context["scheme"] host = request_context["host"] port = request_context["port"] pool = self._new_pool(scheme, host, port, request_context=request_context) self.pools[pool_key] = pool return pool def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used instead. Note that if a new pool does not need to be created for the request, the provided ``pool_kwargs`` are not used. """ u = parse_url(url) return self.connection_from_host( u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs ) def _merge_pool_kwargs(self, override): """ Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary. """ base_pool_kwargs = self.connection_pool_kw.copy() if override: for key, value in override.items(): if value is None: try: del base_pool_kwargs[key] except KeyError: pass else: base_pool_kwargs[key] = value return base_pool_kwargs def _proxy_requires_url_absolute_form(self, parsed_url): """ Indicates if the proxy requires the complete destination URL in the request. Normally this is only needed when not using an HTTP CONNECT tunnel. """ if self.proxy is None: return False return not connection_requires_http_tunnel( self.proxy, self.proxy_config, parsed_url.scheme ) def _validate_proxy_scheme_url_selection(self, url_scheme): """ Validates that were not attempting to do TLS in TLS connections on Python2 or with unsupported SSL implementations. """ if self.proxy is None or url_scheme != "https": return if self.proxy.scheme != "https": return if six.PY2 and not self.proxy_config.use_forwarding_for_https: raise ProxySchemeUnsupported( "Contacting HTTPS destinations through HTTPS proxies " "'via CONNECT tunnels' is not supported in Python 2" ) def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """ u = parse_url(url) self._validate_proxy_scheme_url_selection(u.scheme) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw["assert_same_host"] = False kw["redirect"] = False if "headers" not in kw: kw["headers"] = self.headers.copy() if self._proxy_requires_url_absolute_form(u): response = conn.urlopen(method, url, **kw) else: response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response # Support relative URLs for redirecting. redirect_location = urljoin(url, redirect_location) # RFC 7231, Section 6.4.4 if response.status == 303: method = "GET" retries = kw.get("retries") if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) # Strip headers marked as unsafe to forward to the redirected location. # Check remove_headers_on_redirect to avoid a potential network call within # conn.is_same_host() which may use socket.gethostbyname() in the future. if retries.remove_headers_on_redirect and not conn.is_same_host( redirect_location ): headers = list(six.iterkeys(kw["headers"])) for header in headers: if header.lower() in retries.remove_headers_on_redirect: kw["headers"].pop(header, None) try: retries = retries.increment(method, url, response=response, _pool=conn) except MaxRetryError: if retries.raise_on_redirect: response.drain_conn() raise return response kw["retries"] = retries kw["redirect"] = redirect log.info("Redirecting %s -> %s", url, redirect_location) response.drain_conn() return self.urlopen(method, redirect_location, **kw) class ProxyManager(PoolManager): """ Behaves just like :class:`PoolManager`, but sends all requests through the defined proxy, using the CONNECT method for HTTPS URLs. :param proxy_url: The URL of the proxy to be used. :param proxy_headers: A dictionary containing headers that will be sent to the proxy. In case of HTTP they are being sent with each request, while in the HTTPS/CONNECT case they are sent only once. Could be used for proxy authentication. :param proxy_ssl_context: The proxy SSL context is used to establish the TLS connection to the proxy when using HTTPS proxies. :param use_forwarding_for_https: (Defaults to False) If set to True will forward requests to the HTTPS proxy to be made on behalf of the client instead of creating a TLS tunnel via the CONNECT method. **Enabling this flag means that request and response headers and content will be visible from the HTTPS proxy** whereas tunneling keeps request and response headers and content private. IP address, target hostname, SNI, and port are always visible to an HTTPS proxy even when this flag is disabled. Example: >>> proxy = urllib3.ProxyManager('http://localhost:3128/') >>> r1 = proxy.request('GET', 'http://google.com/') >>> r2 = proxy.request('GET', 'http://httpbin.org/') >>> len(proxy.pools) 1 >>> r3 = proxy.request('GET', 'https://httpbin.org/') >>> r4 = proxy.request('GET', 'https://twitter.com/') >>> len(proxy.pools) 3 """ def __init__( self, proxy_url, num_pools=10, headers=None, proxy_headers=None, proxy_ssl_context=None, use_forwarding_for_https=False, **connection_pool_kw ): if isinstance(proxy_url, HTTPConnectionPool): proxy_url = "%s://%s:%i" % ( proxy_url.scheme, proxy_url.host, proxy_url.port, ) proxy = parse_url(proxy_url) if proxy.scheme not in ("http", "https"): raise ProxySchemeUnknown(proxy.scheme) if not proxy.port: port = port_by_scheme.get(proxy.scheme, 80) proxy = proxy._replace(port=port) self.proxy = proxy self.proxy_headers = proxy_headers or {} self.proxy_ssl_context = proxy_ssl_context self.proxy_config = ProxyConfig(proxy_ssl_context, use_forwarding_for_https) connection_pool_kw["_proxy"] = self.proxy connection_pool_kw["_proxy_headers"] = self.proxy_headers connection_pool_kw["_proxy_config"] = self.proxy_config super(ProxyManager, self).__init__(num_pools, headers, **connection_pool_kw) def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): if scheme == "https": return super(ProxyManager, self).connection_from_host( host, port, scheme, pool_kwargs=pool_kwargs ) return super(ProxyManager, self).connection_from_host( self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs ) def _set_proxy_headers(self, url, headers=None): """ Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user. """ headers_ = {"Accept": "*/*"} netloc = parse_url(url).netloc if netloc: headers_["Host"] = netloc if headers: headers_.update(headers) return headers_ def urlopen(self, method, url, redirect=True, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." u = parse_url(url) if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme): # For connections using HTTP CONNECT, httplib sets the necessary # headers on the CONNECT to the proxy. If we're not using CONNECT, # we'll definitely need to set 'Host' at the very least. headers = kw.get("headers", self.headers) kw["headers"] = self._set_proxy_headers(url, headers) return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw) def proxy_from_url(url, **kw): return ProxyManager(proxy_url=url, **kw)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/poolmanager.py
poolmanager.py
from __future__ import absolute_import import logging import warnings from logging import NullHandler from . import exceptions from ._version import __version__ from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url from .filepost import encode_multipart_formdata from .poolmanager import PoolManager, ProxyManager, proxy_from_url from .response import HTTPResponse from .util.request import make_headers from .util.retry import Retry from .util.timeout import Timeout from .util.url import get_host __author__ = "Andrey Petrov ([email protected])" __license__ = "MIT" __version__ = __version__ __all__ = ( "HTTPConnectionPool", "HTTPSConnectionPool", "PoolManager", "ProxyManager", "HTTPResponse", "Retry", "Timeout", "add_stderr_logger", "connection_from_url", "disable_warnings", "encode_multipart_formdata", "get_host", "make_headers", "proxy_from_url", ) logging.getLogger(__name__).addHandler(NullHandler()) def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another package. logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) logger.addHandler(handler) logger.setLevel(level) logger.debug("Added a stderr logging handler to logger: %s", __name__) return handler # ... Clean up. del NullHandler # All warning filters *must* be appended unless you're really certain that they # shouldn't be: otherwise, it's very hard for users to use most Python # mechanisms to silence them. # SecurityWarning's always go off by default. warnings.simplefilter("always", exceptions.SecurityWarning, append=True) # SubjectAltNameWarning's should go off once per host warnings.simplefilter("default", exceptions.SubjectAltNameWarning, append=True) # InsecurePlatformWarning's don't vary between requests, so we keep it default. warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True) # SNIMissingWarnings should go off only once. warnings.simplefilter("default", exceptions.SNIMissingWarning, append=True) def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter("ignore", category)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/__init__.py
__init__.py
from __future__ import absolute_import try: from collections.abc import Mapping, MutableMapping except ImportError: from collections import Mapping, MutableMapping try: from threading import RLock except ImportError: # Platform-specific: No threads available class RLock: def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): pass from collections import OrderedDict from .exceptions import InvalidHeader from .packages import six from .packages.six import iterkeys, itervalues __all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"] _Null = object() class RecentlyUsedContainer(MutableMapping): """ Provides a thread-safe dict-like container which maintains up to ``maxsize`` keys while throwing away the least-recently-used keys beyond ``maxsize``. :param maxsize: Maximum number of recent elements to retain. :param dispose_func: Every time an item is evicted from the container, ``dispose_func(value)`` is called. Callback which will get called """ ContainerCls = OrderedDict def __init__(self, maxsize=10, dispose_func=None): self._maxsize = maxsize self.dispose_func = dispose_func self._container = self.ContainerCls() self.lock = RLock() def __getitem__(self, key): # Re-insert the item, moving it to the end of the eviction line. with self.lock: item = self._container.pop(key) self._container[key] = item return item def __setitem__(self, key, value): evicted_value = _Null with self.lock: # Possibly evict the existing value of 'key' evicted_value = self._container.get(key, _Null) self._container[key] = value # If we didn't evict an existing value, we might have to evict the # least recently used item from the beginning of the container. if len(self._container) > self._maxsize: _key, evicted_value = self._container.popitem(last=False) if self.dispose_func and evicted_value is not _Null: self.dispose_func(evicted_value) def __delitem__(self, key): with self.lock: value = self._container.pop(key) if self.dispose_func: self.dispose_func(value) def __len__(self): with self.lock: return len(self._container) def __iter__(self): raise NotImplementedError( "Iteration over this class is unlikely to be threadsafe." ) def clear(self): with self.lock: # Copy pointers to all values, then wipe the mapping values = list(itervalues(self._container)) self._container.clear() if self.dispose_func: for value in values: self.dispose_func(value) def keys(self): with self.lock: return list(iterkeys(self._container)) class HTTPHeaderDict(MutableMapping): """ :param headers: An iterable of field-value pairs. Must not contain multiple field names when compared case-insensitively. :param kwargs: Additional field-value pairs to pass in to ``dict.update``. A ``dict`` like container for storing HTTP Headers. Field names are stored and compared case-insensitively in compliance with RFC 7230. Iteration provides the first case-sensitive key seen for each case-insensitive pair. Using ``__setitem__`` syntax overwrites fields that compare equal case-insensitively in order to maintain ``dict``'s api. For fields that compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add`` in a loop. If multiple fields that are equal case-insensitively are passed to the constructor or ``.update``, the behavior is undefined and some will be lost. >>> headers = HTTPHeaderDict() >>> headers.add('Set-Cookie', 'foo=bar') >>> headers.add('set-cookie', 'baz=quxx') >>> headers['content-length'] = '7' >>> headers['SET-cookie'] 'foo=bar, baz=quxx' >>> headers['Content-Length'] '7' """ def __init__(self, headers=None, **kwargs): super(HTTPHeaderDict, self).__init__() self._container = OrderedDict() if headers is not None: if isinstance(headers, HTTPHeaderDict): self._copy_from(headers) else: self.extend(headers) if kwargs: self.extend(kwargs) def __setitem__(self, key, val): self._container[key.lower()] = [key, val] return self._container[key.lower()] def __getitem__(self, key): val = self._container[key.lower()] return ", ".join(val[1:]) def __delitem__(self, key): del self._container[key.lower()] def __contains__(self, key): return key.lower() in self._container def __eq__(self, other): if not isinstance(other, Mapping) and not hasattr(other, "keys"): return False if not isinstance(other, type(self)): other = type(self)(other) return dict((k.lower(), v) for k, v in self.itermerged()) == dict( (k.lower(), v) for k, v in other.itermerged() ) def __ne__(self, other): return not self.__eq__(other) if six.PY2: # Python 2 iterkeys = MutableMapping.iterkeys itervalues = MutableMapping.itervalues __marker = object() def __len__(self): return len(self._container) def __iter__(self): # Only provide the originally cased names for vals in self._container.values(): yield vals[0] def pop(self, key, default=__marker): """D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. """ # Using the MutableMapping function directly fails due to the private marker. # Using ordinary dict.pop would expose the internal structures. # So let's reinvent the wheel. try: value = self[key] except KeyError: if default is self.__marker: raise return default else: del self[key] return value def discard(self, key): try: del self[key] except KeyError: pass def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' """ key_lower = key.lower() new_vals = [key, val] # Keep the common case aka no item present as fast as possible vals = self._container.setdefault(key_lower, new_vals) if new_vals is not vals: vals.append(val) def extend(self, *args, **kwargs): """Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__ """ if len(args) > 1: raise TypeError( "extend() takes at most 1 positional " "arguments ({0} given)".format(len(args)) ) other = args[0] if len(args) >= 1 else () if isinstance(other, HTTPHeaderDict): for key, val in other.iteritems(): self.add(key, val) elif isinstance(other, Mapping): for key in other: self.add(key, other[key]) elif hasattr(other, "keys"): for key in other.keys(): self.add(key, other[key]) else: for key, value in other: self.add(key, value) for key, value in kwargs.items(): self.add(key, value) def getlist(self, key, default=__marker): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = self._container[key.lower()] except KeyError: if default is self.__marker: return [] return default else: return vals[1:] # Backwards compatibility for httplib getheaders = getlist getallmatchingheaders = getlist iget = getlist # Backwards compatibility for http.cookiejar get_all = getlist def __repr__(self): return "%s(%s)" % (type(self).__name__, dict(self.itermerged())) def _copy_from(self, other): for key in other: val = other.getlist(key) if isinstance(val, list): # Don't need to convert tuples val = list(val) self._container[key.lower()] = [key] + val def copy(self): clone = type(self)() clone._copy_from(self) return clone def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = self._container[key.lower()] for val in vals[1:]: yield vals[0], val def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = self._container[key.lower()] yield val[0], ", ".join(val[1:]) def items(self): return list(self.iteritems()) @classmethod def from_httplib(cls, message): # Python 2 """Read headers from a Python 2 httplib message object.""" # python2.7 does not expose a proper API for exporting multiheaders # efficiently. This function re-reads raw lines from the message # object and extracts the multiheaders properly. obs_fold_continued_leaders = (" ", "\t") headers = [] for line in message.headers: if line.startswith(obs_fold_continued_leaders): if not headers: # We received a header line that starts with OWS as described # in RFC-7230 S3.2.4. This indicates a multiline header, but # there exists no previous header to which we can attach it. raise InvalidHeader( "Header continuation with no previous header: %s" % line ) else: key, value = headers[-1] headers[-1] = (key, value + " " + line.strip()) continue key, value = line.split(":", 1) headers.append((key, value.strip())) return cls(headers)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/_collections.py
_collections.py
from __future__ import absolute_import from .filepost import encode_multipart_formdata from .packages.six.moves.urllib.parse import urlencode __all__ = ["RequestMethods"] class RequestMethods(object): """ Convenience mixin for classes who implement a :meth:`urlopen` method, such as :class:`urllib3.HTTPConnectionPool` and :class:`urllib3.PoolManager`. Provides behavior for making common types of HTTP request methods and decides which type of request field encoding to use. Specifically, :meth:`.request_encode_url` is for sending requests whose fields are encoded in the URL (such as GET, HEAD, DELETE). :meth:`.request_encode_body` is for sending requests whose fields are encoded in the *body* of the request using multipart or www-form-urlencoded (such as for POST, PUT, PATCH). :meth:`.request` is for making any kind of request, it will look up the appropriate encoding format and use one of the above two methods to make the request. Initializer parameters: :param headers: Headers to include with all requests, unless other headers are given explicitly. """ _encode_url_methods = {"DELETE", "GET", "HEAD", "OPTIONS"} def __init__(self, headers=None): self.headers = headers or {} def urlopen( self, method, url, body=None, headers=None, encode_multipart=True, multipart_boundary=None, **kw ): # Abstract raise NotImplementedError( "Classes extending RequestMethods must implement " "their own ``urlopen`` method." ) def request(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used. This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as :meth:`request_encode_url`, :meth:`request_encode_body`, or even the lowest level :meth:`urlopen`. """ method = method.upper() urlopen_kw["request_url"] = url if method in self._encode_url_methods: return self.request_encode_url( method, url, fields=fields, headers=headers, **urlopen_kw ) else: return self.request_encode_body( method, url, fields=fields, headers=headers, **urlopen_kw ) def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if headers is None: headers = self.headers extra_kw = {"headers": headers} extra_kw.update(urlopen_kw) if fields: url += "?" + urlencode(fields) return self.urlopen(method, url, **extra_kw) def request_encode_body( self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw ): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :func:`urllib3.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :func:`urllib.parse.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if headers is None: headers = self.headers extra_kw = {"headers": {}} if fields: if "body" in urlopen_kw: raise TypeError( "request got values for both 'fields' and 'body', can only specify one." ) if encode_multipart: body, content_type = encode_multipart_formdata( fields, boundary=multipart_boundary ) else: body, content_type = ( urlencode(fields), "application/x-www-form-urlencoded", ) extra_kw["body"] = body extra_kw["headers"] = {"Content-Type": content_type} extra_kw["headers"].update(headers) extra_kw.update(urlopen_kw) return self.urlopen(method, url, **extra_kw)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/request.py
request.py
from __future__ import absolute_import from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead # Base Exceptions class HTTPError(Exception): """Base exception used by this module.""" pass class HTTPWarning(Warning): """Base warning used by this module.""" pass class PoolError(HTTPError): """Base exception for errors caused within a pool.""" def __init__(self, pool, message): self.pool = pool HTTPError.__init__(self, "%s: %s" % (pool, message)) def __reduce__(self): # For pickling purposes. return self.__class__, (None, None) class RequestError(PoolError): """Base exception for PoolErrors that have associated URLs.""" def __init__(self, pool, url, message): self.url = url PoolError.__init__(self, pool, message) def __reduce__(self): # For pickling purposes. return self.__class__, (None, self.url, None) class SSLError(HTTPError): """Raised when SSL certificate fails in an HTTPS connection.""" pass class ProxyError(HTTPError): """Raised when the connection to a proxy fails.""" def __init__(self, message, error, *args): super(ProxyError, self).__init__(message, error, *args) self.original_error = error class DecodeError(HTTPError): """Raised when automatic decoding based on Content-Type fails.""" pass class ProtocolError(HTTPError): """Raised when something unexpected happens mid-request/response.""" pass #: Renamed to ProtocolError but aliased for backwards compatibility. ConnectionError = ProtocolError # Leaf Exceptions class MaxRetryError(RequestError): """Raised when the maximum number of retries is exceeded. :param pool: The connection pool :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` :param string url: The requested Url :param exceptions.Exception reason: The underlying error """ def __init__(self, pool, url, reason=None): self.reason = reason message = "Max retries exceeded with url: %s (Caused by %r)" % (url, reason) RequestError.__init__(self, pool, url, message) class HostChangedError(RequestError): """Raised when an existing pool gets a request for a foreign host.""" def __init__(self, pool, url, retries=3): message = "Tried to open a foreign host with url: %s" % url RequestError.__init__(self, pool, url, message) self.retries = retries class TimeoutStateError(HTTPError): """Raised when passing an invalid state to a timeout""" pass class TimeoutError(HTTPError): """Raised when a socket timeout error occurs. Catching this error will catch both :exc:`ReadTimeoutErrors <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`. """ pass class ReadTimeoutError(TimeoutError, RequestError): """Raised when a socket timeout occurs while receiving data from a server""" pass # This timeout error does not have a URL attached and needs to inherit from the # base HTTPError class ConnectTimeoutError(TimeoutError): """Raised when a socket timeout occurs while connecting to a server""" pass class NewConnectionError(ConnectTimeoutError, PoolError): """Raised when we fail to establish a new connection. Usually ECONNREFUSED.""" pass class EmptyPoolError(PoolError): """Raised when a pool runs out of connections and no more are allowed.""" pass class ClosedPoolError(PoolError): """Raised when a request enters a pool after the pool has been closed.""" pass class LocationValueError(ValueError, HTTPError): """Raised when there is something wrong with a given URL input.""" pass class LocationParseError(LocationValueError): """Raised when get_host or similar fails to parse the URL input.""" def __init__(self, location): message = "Failed to parse: %s" % location HTTPError.__init__(self, message) self.location = location class URLSchemeUnknown(LocationValueError): """Raised when a URL input has an unsupported scheme.""" def __init__(self, scheme): message = "Not supported URL scheme %s" % scheme super(URLSchemeUnknown, self).__init__(message) self.scheme = scheme class ResponseError(HTTPError): """Used as a container for an error reason supplied in a MaxRetryError.""" GENERIC_ERROR = "too many error responses" SPECIFIC_ERROR = "too many {status_code} error responses" class SecurityWarning(HTTPWarning): """Warned when performing security reducing actions""" pass class SubjectAltNameWarning(SecurityWarning): """Warned when connecting to a host with a certificate missing a SAN.""" pass class InsecureRequestWarning(SecurityWarning): """Warned when making an unverified HTTPS request.""" pass class SystemTimeWarning(SecurityWarning): """Warned when system time is suspected to be wrong""" pass class InsecurePlatformWarning(SecurityWarning): """Warned when certain TLS/SSL configuration is not available on a platform.""" pass class SNIMissingWarning(HTTPWarning): """Warned when making a HTTPS request without SNI available.""" pass class DependencyWarning(HTTPWarning): """ Warned when an attempt is made to import a module with missing optional dependencies. """ pass class ResponseNotChunked(ProtocolError, ValueError): """Response needs to be chunked in order to read it as chunks.""" pass class BodyNotHttplibCompatible(HTTPError): """ Body should be :class:`http.client.HTTPResponse` like (have an fp attribute which returns raw chunks) for read_chunked(). """ pass class IncompleteRead(HTTPError, httplib_IncompleteRead): """ Response length doesn't match expected Content-Length Subclass of :class:`http.client.IncompleteRead` to allow int value for ``partial`` to avoid creating large objects on streamed reads. """ def __init__(self, partial, expected): super(IncompleteRead, self).__init__(partial, expected) def __repr__(self): return "IncompleteRead(%i bytes read, %i more expected)" % ( self.partial, self.expected, ) class InvalidChunkLength(HTTPError, httplib_IncompleteRead): """Invalid chunk length in a chunked response.""" def __init__(self, response, length): super(InvalidChunkLength, self).__init__( response.tell(), response.length_remaining ) self.response = response self.length = length def __repr__(self): return "InvalidChunkLength(got length %r, %i bytes read)" % ( self.length, self.partial, ) class InvalidHeader(HTTPError): """The header provided was somehow invalid.""" pass class ProxySchemeUnknown(AssertionError, URLSchemeUnknown): """ProxyManager does not support the supplied scheme""" # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. def __init__(self, scheme): # 'localhost' is here because our URL parser parses # localhost:8080 -> scheme=localhost, remove if we fix this. if scheme == "localhost": scheme = None if scheme is None: message = "Proxy URL had no scheme, should start with http:// or https://" else: message = ( "Proxy URL had unsupported scheme %s, should use http:// or https://" % scheme ) super(ProxySchemeUnknown, self).__init__(message) class ProxySchemeUnsupported(ValueError): """Fetching HTTPS resources through HTTPS proxies is unsupported""" pass class HeaderParsingError(HTTPError): """Raised by assert_header_parsing, but we convert it to a log.warning statement.""" def __init__(self, defects, unparsed_data): message = "%s, unparsed data: %r" % (defects or "Unknown", unparsed_data) super(HeaderParsingError, self).__init__(message) class UnrewindableBodyError(HTTPError): """urllib3 encountered an error when trying to rewind a body""" pass
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/exceptions.py
exceptions.py
from __future__ import absolute_import import email.utils import mimetypes import re from .packages import six def guess_content_type(filename, default="application/octet-stream"): """ Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`. """ if filename: return mimetypes.guess_type(filename)[0] or default return default def format_header_param_rfc2231(name, value): """ Helper function to format and quote a single header parameter using the strategy defined in RFC 2231. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows `RFC 2388 Section 4.4 <https://tools.ietf.org/html/rfc2388#section-4.4>`_. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as ``bytes`` or `str``. :ret: An RFC-2231-formatted unicode string. """ if isinstance(value, six.binary_type): value = value.decode("utf-8") if not any(ch in value for ch in '"\\\r\n'): result = u'%s="%s"' % (name, value) try: result.encode("ascii") except (UnicodeEncodeError, UnicodeDecodeError): pass else: return result if six.PY2: # Python 2: value = value.encode("utf-8") # encode_rfc2231 accepts an encoded string and returns an ascii-encoded # string in Python 2 but accepts and returns unicode strings in Python 3 value = email.utils.encode_rfc2231(value, "utf-8") value = "%s*=%s" % (name, value) if six.PY2: # Python 2: value = value.decode("utf-8") return value _HTML5_REPLACEMENTS = { u"\u0022": u"%22", # Replace "\" with "\\". u"\u005C": u"\u005C\u005C", } # All control characters from 0x00 to 0x1F *except* 0x1B. _HTML5_REPLACEMENTS.update( { six.unichr(cc): u"%{:02X}".format(cc) for cc in range(0x00, 0x1F + 1) if cc not in (0x1B,) } ) def _replace_multiple(value, needles_and_replacements): def replacer(match): return needles_and_replacements[match.group(0)] pattern = re.compile( r"|".join([re.escape(needle) for needle in needles_and_replacements.keys()]) ) result = pattern.sub(replacer, value) return result def format_header_param_html5(name, value): """ Helper function to format and quote a single header parameter using the HTML5 strategy. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows the `HTML5 Working Draft Section 4.10.22.7`_ and matches the behavior of curl and modern browsers. .. _HTML5 Working Draft Section 4.10.22.7: https://w3c.github.io/html/sec-forms.html#multipart-form-data :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as ``bytes`` or `str``. :ret: A unicode string, stripped of troublesome characters. """ if isinstance(value, six.binary_type): value = value.decode("utf-8") value = _replace_multiple(value, _HTML5_REPLACEMENTS) return u'%s="%s"' % (name, value) # For backwards-compatibility. format_header_param = format_header_param_html5 class RequestField(object): """ A data container for request body parameters. :param name: The name of this request field. Must be unicode. :param data: The data/value body. :param filename: An optional filename of the request field. Must be unicode. :param headers: An optional dict-like object of headers to initially use for the field. :param header_formatter: An optional callable that is used to encode and format the headers. By default, this is :func:`format_header_param_html5`. """ def __init__( self, name, data, filename=None, headers=None, header_formatter=format_header_param_html5, ): self._name = name self._filename = filename self.data = data self.headers = {} if headers: self.headers = dict(headers) self.header_formatter = header_formatter @classmethod def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5): """ A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode. """ if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = guess_content_type(filename) else: filename = None content_type = None data = value request_param = cls( fieldname, data, filename=filename, header_formatter=header_formatter ) request_param.make_multipart(content_type=content_type) return request_param def _render_part(self, name, value): """ Overridable helper function to format a single header parameter. By default, this calls ``self.header_formatter``. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ return self.header_formatter(name, value) def _render_parts(self, header_parts): """ Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., 'Content-Disposition' fields. :param header_parts: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`. """ parts = [] iterable = header_parts if isinstance(header_parts, dict): iterable = header_parts.items() for name, value in iterable: if value is not None: parts.append(self._render_part(name, value)) return u"; ".join(parts) def render_headers(self): """ Renders the headers for this request field. """ lines = [] sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append(u"%s: %s" % (sort_key, self.headers[sort_key])) for header_name, header_value in self.headers.items(): if header_name not in sort_keys: if header_value: lines.append(u"%s: %s" % (header_name, header_value)) lines.append(u"\r\n") return u"\r\n".join(lines) def make_multipart( self, content_disposition=None, content_type=None, content_location=None ): """ Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body. """ self.headers["Content-Disposition"] = content_disposition or u"form-data" self.headers["Content-Disposition"] += u"; ".join( [ u"", self._render_parts( ((u"name", self._name), (u"filename", self._filename)) ), ] ) self.headers["Content-Type"] = content_type self.headers["Content-Location"] = content_location
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/fields.py
fields.py
from __future__ import absolute_import import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from cryptography.hazmat.backends.openssl.x509 import _Certificate try: from cryptography.x509 import UnsupportedExtension except ImportError: # UnsupportedExtension is gone in cryptography >= 2.1.0 class UnsupportedExtension(Exception): pass from io import BytesIO from socket import error as SocketError from socket import timeout try: # Platform-specific: Python 2 from socket import _fileobject except ImportError: # Platform-specific: Python 3 _fileobject = None from ..packages.backports.makefile import backport_makefile import logging import ssl import sys from .. import util from ..packages import six from ..util.ssl_ import PROTOCOL_TLS_CLIENT __all__ = ["inject_into_urllib3", "extract_from_urllib3"] # SNI always works. HAS_SNI = True # Map from urllib3 to PyOpenSSL compatible parameter-values. _openssl_versions = { util.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, } if hasattr(ssl, "PROTOCOL_SSLv3") and hasattr(OpenSSL.SSL, "SSLv3_METHOD"): _openssl_versions[ssl.PROTOCOL_SSLv3] = OpenSSL.SSL.SSLv3_METHOD if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD _stdlib_to_openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } _openssl_to_stdlib_verify = dict((v, k) for k, v in _stdlib_to_openssl_verify.items()) # OpenSSL will only write 16K at a time SSL_WRITE_BLOCKSIZE = 16384 orig_util_HAS_SNI = util.HAS_SNI orig_util_SSLContext = util.ssl_.SSLContext log = logging.getLogger(__name__) def inject_into_urllib3(): "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." _validate_dependencies_met() util.SSLContext = PyOpenSSLContext util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True def extract_from_urllib3(): "Undo monkey-patching by :func:`inject_into_urllib3`." util.SSLContext = orig_util_SSLContext util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_PYOPENSSL = False util.ssl_.IS_PYOPENSSL = False def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Extensions, "get_extension_for_class", None) is None: raise ImportError( "'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer." ) # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 # attribute is only present on those versions. from OpenSSL.crypto import X509 x509 = X509() if getattr(x509, "_x509", None) is None: raise ImportError( "'pyOpenSSL' module missing required functionality. " "Try upgrading to v0.14 or newer." ) 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 def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except ( x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError, ) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ("DNS", name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names class WrappedSocket(object): """API-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. """ def __init__(self, connection, socket, suppress_ragged_eofs=True): self.connection = connection self.socket = socket self.suppress_ragged_eofs = suppress_ragged_eofs self._makefile_refs = 0 self._closed = False def fileno(self): return self.socket.fileno() # Copy-pasted from Python 3.5 source code def _decref_socketios(self): if self._makefile_refs > 0: self._makefile_refs -= 1 if self._closed: self.close() def recv(self, *args, **kwargs): try: data = self.connection.recv(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): return b"" else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b"" else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout("The read operation timed out") else: return self.recv(*args, **kwargs) # TLS 1.3 post-handshake authentication except OpenSSL.SSL.Error as e: raise ssl.SSLError("read error: %r" % e) else: return data def recv_into(self, *args, **kwargs): try: return self.connection.recv_into(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout("The read operation timed out") else: return self.recv_into(*args, **kwargs) # TLS 1.3 post-handshake authentication except OpenSSL.SSL.Error as e: raise ssl.SSLError("read error: %r" % e) def settimeout(self, timeout): return self.socket.settimeout(timeout) def _send_until_done(self, data): while True: try: return self.connection.send(data) except OpenSSL.SSL.WantWriteError: if not util.wait_for_write(self.socket, self.socket.gettimeout()): raise timeout() continue except OpenSSL.SSL.SysCallError as e: raise SocketError(str(e)) def sendall(self, data): total_sent = 0 while total_sent < len(data): sent = self._send_until_done( data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] ) total_sent += sent def shutdown(self): # FIXME rethrow compatible exceptions should we ever use this self.connection.shutdown() def close(self): if self._makefile_refs < 1: try: self._closed = True return self.connection.close() except OpenSSL.SSL.Error: return else: self._makefile_refs -= 1 def getpeercert(self, binary_form=False): x509 = self.connection.get_peer_certificate() if not x509: return x509 if binary_form: return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) return { "subject": ((("commonName", x509.get_subject().CN),),), "subjectAltName": get_subj_alt_name(x509), } def version(self): return self.connection.get_protocol_version_name() def _reuse(self): self._makefile_refs += 1 def _drop(self): if self._makefile_refs < 1: self.close() else: self._makefile_refs -= 1 if _fileobject: # Platform-specific: Python 2 def makefile(self, mode, bufsize=-1): self._makefile_refs += 1 return _fileobject(self, mode, bufsize, close=True) else: # Platform-specific: Python 3 makefile = backport_makefile WrappedSocket.makefile = makefile class PyOpenSSLContext(object): """ I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. """ def __init__(self, protocol): self.protocol = _openssl_versions[protocol] self._ctx = OpenSSL.SSL.Context(self.protocol) self._options = 0 self.check_hostname = False @property def options(self): return self._options @options.setter def options(self, value): self._options = value self._ctx.set_options(value) @property def verify_mode(self): return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) def set_default_verify_paths(self): self._ctx.set_default_verify_paths() def set_ciphers(self, ciphers): if isinstance(ciphers, six.text_type): ciphers = ciphers.encode("utf-8") self._ctx.set_cipher_list(ciphers) 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") try: self._ctx.load_verify_locations(cafile, capath) if cadata is not None: self._ctx.load_verify_locations(BytesIO(cadata)) except OpenSSL.SSL.Error as e: raise ssl.SSLError("unable to load trusted certificates: %r" % e) def load_cert_chain(self, certfile, keyfile=None, password=None): self._ctx.use_certificate_chain_file(certfile) if password is not None: if not isinstance(password, six.binary_type): password = password.encode("utf-8") self._ctx.set_passwd_cb(lambda *_: password) self._ctx.use_privatekey_file(keyfile or certfile) def set_alpn_protocols(self, protocols): protocols = [six.ensure_binary(p) for p in protocols] return self._ctx.set_alpn_protos(protocols) 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) def _verify_callback(cnx, x509, err_no, err_depth, return_code): return err_no == 0
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/contrib/pyopenssl.py
pyopenssl.py
from __future__ import absolute_import import io import logging import warnings from ..exceptions import ( HTTPError, HTTPWarning, MaxRetryError, ProtocolError, SSLError, TimeoutError, ) from ..packages.six.moves.urllib.parse import urljoin from ..request import RequestMethods from ..response import HTTPResponse from ..util.retry import Retry from ..util.timeout import Timeout from . import _appengine_environ try: from google.appengine.api import urlfetch except ImportError: urlfetch = None log = logging.getLogger(__name__) class AppEnginePlatformWarning(HTTPWarning): pass class AppEnginePlatformError(HTTPError): pass class AppEngineManager(RequestMethods): """ Connection manager for Google App Engine sandbox applications. This manager uses the URLFetch service directly instead of using the emulated httplib, and is subject to URLFetch limitations as described in the App Engine documentation `here <https://cloud.google.com/appengine/docs/python/urlfetch>`_. Notably it will raise an :class:`AppEnginePlatformError` if: * URLFetch is not available. * If you attempt to use this on App Engine Flexible, as full socket support is available. * If a request size is more than 10 megabytes. * If a response size is more than 32 megabytes. * If you use an unsupported request method such as OPTIONS. Beyond those cases, it will raise normal urllib3 errors. """ def __init__( self, headers=None, retries=None, validate_certificate=True, urlfetch_retries=True, ): if not urlfetch: raise AppEnginePlatformError( "URLFetch is not available in this environment." ) warnings.warn( "urllib3 is using URLFetch on Google App Engine sandbox instead " "of sockets. To use sockets directly instead of URLFetch see " "https://urllib3.readthedocs.io/en/1.26.x/reference/urllib3.contrib.html.", AppEnginePlatformWarning, ) RequestMethods.__init__(self, headers) self.validate_certificate = validate_certificate self.urlfetch_retries = urlfetch_retries self.retries = retries or Retry.DEFAULT def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # Return False to re-raise any potential exceptions return False def urlopen( self, method, url, body=None, headers=None, retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT, **response_kw ): retries = self._get_retries(retries, redirect) try: follow_redirects = redirect and retries.redirect != 0 and retries.total response = urlfetch.fetch( url, payload=body, method=method, headers=headers or {}, allow_truncated=False, follow_redirects=self.urlfetch_retries and follow_redirects, deadline=self._get_absolute_timeout(timeout), validate_certificate=self.validate_certificate, ) except urlfetch.DeadlineExceededError as e: raise TimeoutError(self, e) except urlfetch.InvalidURLError as e: if "too large" in str(e): raise AppEnginePlatformError( "URLFetch request too large, URLFetch only " "supports requests up to 10mb in size.", e, ) raise ProtocolError(e) except urlfetch.DownloadError as e: if "Too many redirects" in str(e): raise MaxRetryError(self, url, reason=e) raise ProtocolError(e) except urlfetch.ResponseTooLargeError as e: raise AppEnginePlatformError( "URLFetch response too large, URLFetch only supports" "responses up to 32mb in size.", e, ) except urlfetch.SSLCertificateError as e: raise SSLError(e) except urlfetch.InvalidMethodError as e: raise AppEnginePlatformError( "URLFetch does not support method: %s" % method, e ) http_response = self._urlfetch_response_to_http_response( response, retries=retries, **response_kw ) # Handle redirect? redirect_location = redirect and http_response.get_redirect_location() if redirect_location: # Check for redirect response if self.urlfetch_retries and retries.raise_on_redirect: raise MaxRetryError(self, url, "too many redirects") else: if http_response.status == 303: method = "GET" try: retries = retries.increment( method, url, response=http_response, _pool=self ) except MaxRetryError: if retries.raise_on_redirect: raise MaxRetryError(self, url, "too many redirects") return http_response retries.sleep_for_retry(http_response) log.debug("Redirecting %s -> %s", url, redirect_location) redirect_url = urljoin(url, redirect_location) return self.urlopen( method, redirect_url, body, headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw ) # Check if we should retry the HTTP response. has_retry_after = bool(http_response.getheader("Retry-After")) if retries.is_retry(method, http_response.status, has_retry_after): retries = retries.increment(method, url, response=http_response, _pool=self) log.debug("Retry: %s", url) retries.sleep(http_response) return self.urlopen( method, url, body=body, headers=headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw ) return http_response def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw): if is_prod_appengine(): # Production GAE handles deflate encoding automatically, but does # not remove the encoding header. content_encoding = urlfetch_resp.headers.get("content-encoding") if content_encoding == "deflate": del urlfetch_resp.headers["content-encoding"] transfer_encoding = urlfetch_resp.headers.get("transfer-encoding") # We have a full response's content, # so let's make sure we don't report ourselves as chunked data. if transfer_encoding == "chunked": encodings = transfer_encoding.split(",") encodings.remove("chunked") urlfetch_resp.headers["transfer-encoding"] = ",".join(encodings) original_response = HTTPResponse( # In order for decoding to work, we must present the content as # a file-like object. body=io.BytesIO(urlfetch_resp.content), msg=urlfetch_resp.header_msg, headers=urlfetch_resp.headers, status=urlfetch_resp.status_code, **response_kw ) return HTTPResponse( body=io.BytesIO(urlfetch_resp.content), headers=urlfetch_resp.headers, status=urlfetch_resp.status_code, original_response=original_response, **response_kw ) def _get_absolute_timeout(self, timeout): if timeout is Timeout.DEFAULT_TIMEOUT: return None # Defer to URLFetch's default. if isinstance(timeout, Timeout): if timeout._read is not None or timeout._connect is not None: warnings.warn( "URLFetch does not support granular timeout settings, " "reverting to total or default URLFetch timeout.", AppEnginePlatformWarning, ) return timeout.total return timeout def _get_retries(self, retries, redirect): if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if retries.connect or retries.read or retries.redirect: warnings.warn( "URLFetch only supports total retries and does not " "recognize connect, read, or redirect retry parameters.", AppEnginePlatformWarning, ) return retries # Alias methods from _appengine_environ to maintain public API interface. is_appengine = _appengine_environ.is_appengine is_appengine_sandbox = _appengine_environ.is_appengine_sandbox is_local_appengine = _appengine_environ.is_local_appengine is_prod_appengine = _appengine_environ.is_prod_appengine is_prod_appengine_mvms = _appengine_environ.is_prod_appengine_mvms
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/contrib/appengine.py
appengine.py
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ..util.ssl_ import PROTOCOL_TLS_CLIENT from ._securetransport.bindings import CoreFoundation, Security, SecurityConst from ._securetransport.low_level import ( _assert_no_error, _build_tls_unknown_ca_alert, _cert_array_from_pem, _create_cfstring_array, _load_client_cert_chain, _temporary_keychain, ) try: # Platform-specific: Python 2 from socket import _fileobject except ImportError: # Platform-specific: Python 3 _fileobject = None from ..packages.backports.makefile import backport_makefile __all__ = ["inject_into_urllib3", "extract_from_urllib3"] # SNI always works HAS_SNI = True orig_util_HAS_SNI = util.HAS_SNI orig_util_SSLContext = util.ssl_.SSLContext # This dictionary is used by the read callback to obtain a handle to the # calling wrapped socket. This is a pretty silly approach, but for now it'll # do. I feel like I should be able to smuggle a handle to the wrapped socket # directly in the SSLConnectionRef, but for now this approach will work I # guess. # # We need to lock around this structure for inserts, but we don't do it for # reads/writes in the callbacks. The reasoning here goes as follows: # # 1. It is not possible to call into the callbacks before the dictionary is # populated, so once in the callback the id must be in the dictionary. # 2. The callbacks don't mutate the dictionary, they only read from it, and # so cannot conflict with any of the insertions. # # This is good: if we had to lock in the callbacks we'd drastically slow down # the performance of this code. _connection_refs = weakref.WeakValueDictionary() _connection_ref_lock = threading.Lock() # Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over # for no better reason than we need *a* limit, and this one is right there. SSL_WRITE_BLOCKSIZE = 16384 # This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to # individual cipher suites. We need to do this because this is how # SecureTransport wants them. CIPHER_SUITES = [ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_AES_256_GCM_SHA384, SecurityConst.TLS_AES_128_GCM_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_AES_128_CCM_8_SHA256, SecurityConst.TLS_AES_128_CCM_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256, SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA, ] # Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of # TLSv1 and a high of TLSv1.2. For everything else, we pin to that version. # TLSv1 to 1.2 are supported on macOS 10.8+ _protocol_to_min_max = { util.PROTOCOL_TLS: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12), PROTOCOL_TLS_CLIENT: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12), } if hasattr(ssl, "PROTOCOL_SSLv2"): _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = ( SecurityConst.kSSLProtocol2, SecurityConst.kSSLProtocol2, ) if hasattr(ssl, "PROTOCOL_SSLv3"): _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = ( SecurityConst.kSSLProtocol3, SecurityConst.kSSLProtocol3, ) if hasattr(ssl, "PROTOCOL_TLSv1"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = ( SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol1, ) if hasattr(ssl, "PROTOCOL_TLSv1_1"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = ( SecurityConst.kTLSProtocol11, SecurityConst.kTLSProtocol11, ) if hasattr(ssl, "PROTOCOL_TLSv1_2"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = ( SecurityConst.kTLSProtocol12, SecurityConst.kTLSProtocol12, ) def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.SSLContext = SecureTransportContext util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_urllib3`. """ util.SSLContext = orig_util_SSLContext util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False util.ssl_.IS_SECURETRANSPORT = False def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, "timed out") remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, "timed out") chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal # We need to keep these two objects references alive: if they get GC'd while # in use then SecureTransport could attempt to call a function that is in freed # memory. That would be...uh...bad. Yeah, that's the word. Bad. _read_callback_pointer = Security.SSLReadFunc(_read_callback) _write_callback_pointer = Security.SSLWriteFunc(_write_callback) class WrappedSocket(object): """ API-compatibility wrapper for Python's OpenSSL wrapped socket object. Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage collector of PyPy. """ def __init__(self, socket): self.socket = socket self.context = None self._makefile_refs = 0 self._closed = False self._exception = None self._keychain = None self._keychain_dir = None self._client_cert_chain = None # We save off the previously-configured timeout and then set it to # zero. This is done because we use select and friends to handle the # timeouts, but if we leave the timeout set on the lower socket then # Python will "kindly" call select on that socket again for us. Avoid # that by forcing the timeout to zero. self._timeout = self.socket.gettimeout() self.socket.settimeout(0) @contextlib.contextmanager def _raise_on_error(self): """ A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. """ self._exception = None # We explicitly don't catch around this yield because in the unlikely # event that an exception was hit in the block we don't want to swallow # it. yield if self._exception is not None: exception, self._exception = self._exception, None self.close() raise exception def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result) def _set_alpn_protocols(self, protocols): """ Sets up the ALPN protocols on the context. """ if not protocols: return protocols_arr = _create_cfstring_array(protocols) try: result = Security.SSLSetALPNProtocols(self.context, protocols_arr) _assert_no_error(result) finally: CoreFoundation.CFRelease(protocols_arr) def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. Raises an SSLError if the connection is not trusted. """ # If we disabled cert validation, just say: cool. if not verify: return successes = ( SecurityConst.kSecTrustResultUnspecified, SecurityConst.kSecTrustResultProceed, ) try: trust_result = self._evaluate_trust(trust_bundle) if trust_result in successes: return reason = "error code: %d" % (trust_result,) except Exception as e: # Do not trust on error reason = "exception: %r" % (e,) # SecureTransport does not send an alert nor shuts down the connection. rec = _build_tls_unknown_ca_alert(self.version()) self.socket.sendall(rec) # close the connection immediately # l_onoff = 1, activate linger # l_linger = 0, linger for 0 seoncds opts = struct.pack("ii", 1, 0) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, opts) self.close() raise ssl.SSLError("certificate verify failed, %s" % reason) def _evaluate_trust(self, trust_bundle): # We want data in memory, so load it up. if os.path.isfile(trust_bundle): with open(trust_bundle, "rb") as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: # Get a CFArray that contains the certs we want. cert_array = _cert_array_from_pem(trust_bundle) # Ok, now the hard part. We want to get the SecTrustRef that ST has # created for this connection, shove our CAs into it, tell ST to # ignore everything else it knows, and then ask if it can build a # chain. This is a buuuunch of code. result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust)) _assert_no_error(result) if not trust: raise ssl.SSLError("Failed to copy trust reference") result = Security.SecTrustSetAnchorCertificates(trust, cert_array) _assert_no_error(result) result = Security.SecTrustSetAnchorCertificatesOnly(trust, True) _assert_no_error(result) trust_result = Security.SecTrustResultType() result = Security.SecTrustEvaluate(trust, ctypes.byref(trust_result)) _assert_no_error(result) finally: if trust: CoreFoundation.CFRelease(trust) if cert_array is not None: CoreFoundation.CFRelease(cert_array) return trust_result.value def handshake( self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase, alpn_protocols, ): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode("utf-8") result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Setup the ALPN protocols. self._set_alpn_protocols(alpn_protocols) # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate(self.context, self._client_cert_chain) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break def fileno(self): return self.socket.fileno() # Copy-pasted from Python 3.5 source code def _decref_socketios(self): if self._makefile_refs > 0: self._makefile_refs -= 1 if self._closed: self.close() def recv(self, bufsiz): buffer = ctypes.create_string_buffer(bufsiz) bytes_read = self.recv_into(buffer, bufsiz) data = buffer[:bytes_read] return data def recv_into(self, buffer, nbytes=None): # Read short on EOF. if self._closed: return 0 if nbytes is None: nbytes = len(buffer) buffer = (ctypes.c_char * nbytes).from_buffer(buffer) processed_bytes = ctypes.c_size_t(0) with self._raise_on_error(): result = Security.SSLRead( self.context, buffer, nbytes, ctypes.byref(processed_bytes) ) # There are some result codes that we want to treat as "not always # errors". Specifically, those are errSSLWouldBlock, # errSSLClosedGraceful, and errSSLClosedNoNotify. if result == SecurityConst.errSSLWouldBlock: # If we didn't process any bytes, then this was just a time out. # However, we can get errSSLWouldBlock in situations when we *did* # read some data, and in those cases we should just read "short" # and return. if processed_bytes.value == 0: # Timed out, no data read. raise socket.timeout("recv timed out") elif result in ( SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify, ): # The remote peer has closed this connection. We should do so as # well. Note that we don't actually return here because in # principle this could actually be fired along with return data. # It's unlikely though. self.close() else: _assert_no_error(result) # Ok, we read and probably succeeded. We should return whatever data # was actually read. return processed_bytes.value def settimeout(self, timeout): self._timeout = timeout def gettimeout(self): return self._timeout def send(self, data): processed_bytes = ctypes.c_size_t(0) with self._raise_on_error(): result = Security.SSLWrite( self.context, data, len(data), ctypes.byref(processed_bytes) ) if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0: # Timed out raise socket.timeout("send timed out") else: _assert_no_error(result) # We sent, and probably succeeded. Tell them how much we sent. return processed_bytes.value def sendall(self, data): total_sent = 0 while total_sent < len(data): sent = self.send(data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]) total_sent += sent def shutdown(self): with self._raise_on_error(): Security.SSLClose(self.context) def close(self): # TODO: should I do clean shutdown here? Do I have to? if self._makefile_refs < 1: self._closed = True if self.context: CoreFoundation.CFRelease(self.context) self.context = None if self._client_cert_chain: CoreFoundation.CFRelease(self._client_cert_chain) self._client_cert_chain = None if self._keychain: Security.SecKeychainDelete(self._keychain) CoreFoundation.CFRelease(self._keychain) shutil.rmtree(self._keychain_dir) self._keychain = self._keychain_dir = None return self.socket.close() else: self._makefile_refs -= 1 def getpeercert(self, binary_form=False): # Urgh, annoying. # # Here's how we do this: # # 1. Call SSLCopyPeerTrust to get hold of the trust object for this # connection. # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf. # 3. To get the CN, call SecCertificateCopyCommonName and process that # string so that it's of the appropriate type. # 4. To get the SAN, we need to do something a bit more complex: # a. Call SecCertificateCopyValues to get the data, requesting # kSecOIDSubjectAltName. # b. Mess about with this dictionary to try to get the SANs out. # # This is gross. Really gross. It's going to be a few hundred LoC extra # just to repeat something that SecureTransport can *already do*. So my # operating assumption at this time is that what we want to do is # instead to just flag to urllib3 that it shouldn't do its own hostname # validation when using SecureTransport. if not binary_form: raise ValueError("SecureTransport only supports dumping binary certs") trust = Security.SecTrustRef() certdata = None der_bytes = None try: # Grab the trust store. result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust)) _assert_no_error(result) if not trust: # Probably we haven't done the handshake yet. No biggie. return None cert_count = Security.SecTrustGetCertificateCount(trust) if not cert_count: # Also a case that might happen if we haven't handshaked. # Handshook? Handshaken? return None leaf = Security.SecTrustGetCertificateAtIndex(trust, 0) assert leaf # Ok, now we want the DER bytes. certdata = Security.SecCertificateCopyData(leaf) assert certdata data_length = CoreFoundation.CFDataGetLength(certdata) data_buffer = CoreFoundation.CFDataGetBytePtr(certdata) der_bytes = ctypes.string_at(data_buffer, data_length) finally: if certdata: CoreFoundation.CFRelease(certdata) if trust: CoreFoundation.CFRelease(trust) return der_bytes def version(self): protocol = Security.SSLProtocol() result = Security.SSLGetNegotiatedProtocolVersion( self.context, ctypes.byref(protocol) ) _assert_no_error(result) if protocol.value == SecurityConst.kTLSProtocol13: raise ssl.SSLError("SecureTransport does not support TLS 1.3") elif protocol.value == SecurityConst.kTLSProtocol12: return "TLSv1.2" elif protocol.value == SecurityConst.kTLSProtocol11: return "TLSv1.1" elif protocol.value == SecurityConst.kTLSProtocol1: return "TLSv1" elif protocol.value == SecurityConst.kSSLProtocol3: return "SSLv3" elif protocol.value == SecurityConst.kSSLProtocol2: return "SSLv2" else: raise ssl.SSLError("Unknown TLS version: %r" % protocol) def _reuse(self): self._makefile_refs += 1 def _drop(self): if self._makefile_refs < 1: self.close() else: self._makefile_refs -= 1 if _fileobject: # Platform-specific: Python 2 def makefile(self, mode, bufsize=-1): self._makefile_refs += 1 return _fileobject(self, mode, bufsize, close=True) else: # Platform-specific: Python 3 def makefile(self, mode="r", buffering=None, *args, **kwargs): # We disable buffering with SecureTransport because it conflicts with # the buffering that ST does internally (see issue #1153 for more). buffering = 0 return backport_makefile(self, mode, buffering, *args, **kwargs) WrappedSocket.makefile = makefile class SecureTransportContext(object): """ I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. """ def __init__(self, protocol): self._min_version, self._max_version = _protocol_to_min_max[protocol] self._options = 0 self._verify = False self._trust_bundle = None self._client_cert = None self._client_key = None self._client_key_passphrase = None self._alpn_protocols = None @property def check_hostname(self): """ SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. """ return True @check_hostname.setter def check_hostname(self, value): """ SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. """ pass @property def options(self): # TODO: Well, crap. # # So this is the bit of the code that is the most likely to cause us # trouble. Essentially we need to enumerate all of the SSL options that # users might want to use and try to see if we can sensibly translate # them, or whether we should just ignore them. return self._options @options.setter def options(self, value): # TODO: Update in line with above. self._options = value @property def verify_mode(self): return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE @verify_mode.setter def verify_mode(self, value): self._verify = True if value == ssl.CERT_REQUIRED else False def set_default_verify_paths(self): # So, this has to do something a bit weird. Specifically, what it does # is nothing. # # This means that, if we had previously had load_verify_locations # called, this does not undo that. We need to do that because it turns # out that the rest of the urllib3 code will attempt to load the # default verify paths if it hasn't been told about any paths, even if # the context itself was sometime earlier. We resolve that by just # ignoring it. pass def load_default_certs(self): return self.set_default_verify_paths() def set_ciphers(self, ciphers): # For now, we just require the default cipher string. if ciphers != util.ssl_.DEFAULT_CIPHERS: raise ValueError("SecureTransport doesn't support custom cipher strings") def load_verify_locations(self, cafile=None, capath=None, cadata=None): # OK, we only really support cadata and cafile. if capath is not None: raise ValueError("SecureTransport does not support cert directories") # Raise if cafile does not exist. if cafile is not None: with open(cafile): pass self._trust_bundle = cafile or cadata def load_cert_chain(self, certfile, keyfile=None, password=None): self._client_cert = certfile self._client_key = keyfile self._client_cert_passphrase = password def set_alpn_protocols(self, protocols): """ Sets the ALPN protocols that will later be set on the context. Raises a NotImplementedError if ALPN is not supported. """ if not hasattr(Security, "SSLSetALPNProtocols"): raise NotImplementedError( "SecureTransport supports ALPN only in macOS 10.12+" ) self._alpn_protocols = [six.ensure_binary(p) for p in protocols] def wrap_socket( self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, ): # So, what do we do here? Firstly, we assert some properties. This is a # stripped down shim, so there is some functionality we don't support. # See PEP 543 for the real deal. assert not server_side assert do_handshake_on_connect assert suppress_ragged_eofs # Ok, we're good to go. Now we want to create the wrapped socket object # and store it in the appropriate place. wrapped_socket = WrappedSocket(sock) # Now we can handshake wrapped_socket.handshake( server_hostname, self._verify, self._trust_bundle, self._min_version, self._max_version, self._client_cert, self._client_key, self._client_key_passphrase, self._alpn_protocols, ) return wrapped_socket
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/contrib/securetransport.py
securetransport.py
from __future__ import absolute_import import warnings from logging import getLogger from ntlm import ntlm from .. import HTTPSConnectionPool from ..packages.six.moves.http_client import HTTPSConnection warnings.warn( "The 'urllib3.contrib.ntlmpool' module is deprecated and will be removed " "in urllib3 v2.0 release, urllib3 is not able to support it properly due " "to reasons listed in issue: https://github.com/urllib3/urllib3/issues/2282. " "If you are a user of this module please comment in the mentioned issue.", DeprecationWarning, ) log = getLogger(__name__) class NTLMConnectionPool(HTTPSConnectionPool): """ Implements an NTLM authentication version of an urllib3 connection pool """ scheme = "https" def __init__(self, user, pw, authurl, *args, **kwargs): """ authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\\username format. pw is the password for the user. """ super(NTLMConnectionPool, self).__init__(*args, **kwargs) self.authurl = authurl self.rawuser = user user_parts = user.split("\\", 1) self.domain = user_parts[0].upper() self.user = user_parts[1] self.pw = pw def _new_conn(self): # Performs the NTLM handshake that secures the connection. The socket # must be kept open while requests are performed. self.num_connections += 1 log.debug( "Starting NTLM HTTPS connection no. %d: https://%s%s", self.num_connections, self.host, self.authurl, ) headers = {"Connection": "Keep-Alive"} req_header = "Authorization" resp_header = "www-authenticate" conn = HTTPSConnection(host=self.host, port=self.port) # Send negotiation message headers[req_header] = "NTLM %s" % ntlm.create_NTLM_NEGOTIATE_MESSAGE( self.rawuser ) log.debug("Request headers: %s", headers) conn.request("GET", self.authurl, None, headers) res = conn.getresponse() reshdr = dict(res.getheaders()) log.debug("Response status: %s %s", res.status, res.reason) log.debug("Response headers: %s", reshdr) log.debug("Response data: %s [...]", res.read(100)) # Remove the reference to the socket, so that it can not be closed by # the response object (we want to keep the socket open) res.fp = None # Server should respond with a challenge message auth_header_values = reshdr[resp_header].split(", ") auth_header_value = None for s in auth_header_values: if s[:5] == "NTLM ": auth_header_value = s[5:] if auth_header_value is None: raise Exception( "Unexpected %s response header: %s" % (resp_header, reshdr[resp_header]) ) # Send authentication message ServerChallenge, NegotiateFlags = ntlm.parse_NTLM_CHALLENGE_MESSAGE( auth_header_value ) auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE( ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags ) headers[req_header] = "NTLM %s" % auth_msg log.debug("Request headers: %s", headers) conn.request("GET", self.authurl, None, headers) res = conn.getresponse() log.debug("Response status: %s %s", res.status, res.reason) log.debug("Response headers: %s", dict(res.getheaders())) log.debug("Response data: %s [...]", res.read()[:100]) if res.status != 200: if res.status == 401: raise Exception("Server rejected request: wrong username or password") raise Exception("Wrong server response: %s %s" % (res.status, res.reason)) res.fp = None log.debug("Connection established") return conn def urlopen( self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, ): if headers is None: headers = {} headers["Connection"] = "Keep-Alive" return super(NTLMConnectionPool, self).urlopen( method, url, body, headers, retries, redirect, assert_same_host )
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/contrib/ntlmpool.py
ntlmpool.py
from __future__ import absolute_import from zdppy_requests.urllib3.contrib import socks from socket import error as SocketError from socket import timeout as SocketTimeout from ..connection import HTTPConnection, HTTPSConnection from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool from ..exceptions import ConnectTimeoutError, NewConnectionError from ..poolmanager import PoolManager from ..util.url import parse_url try: import ssl except ImportError: ssl = None class SOCKSConnection(HTTPConnection): """ A plain-text HTTP connection that connects via a SOCKS proxy. """ def __init__(self, *args, **kwargs): self._socks_options = kwargs.pop("_socks_options") super(SOCKSConnection, self).__init__(*args, **kwargs) def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw["source_address"] = self.source_address if self.socket_options: extra_kw["socket_options"] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options["socks_version"], proxy_addr=self._socks_options["proxy_host"], proxy_port=self._socks_options["proxy_port"], proxy_username=self._socks_options["username"], proxy_password=self._socks_options["password"], proxy_rdns=self._socks_options["rdns"], timeout=self.timeout, **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) return conn # We don't need to duplicate the Verified/Unverified distinction from # urllib3/connection.py here because the HTTPSConnection will already have been # correctly set to either the Verified or Unverified form by that module. This # means the SOCKSHTTPSConnection will automatically be the correct type. class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): pass class SOCKSHTTPConnectionPool(HTTPConnectionPool): ConnectionCls = SOCKSConnection class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): ConnectionCls = SOCKSHTTPSConnection class SOCKSProxyManager(PoolManager): """ A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. """ pool_classes_by_scheme = { "http": SOCKSHTTPConnectionPool, "https": SOCKSHTTPSConnectionPool, } def __init__( self, proxy_url, username=None, password=None, num_pools=10, headers=None, **connection_pool_kw ): parsed = parse_url(proxy_url) if username is None and password is None and parsed.auth is not None: split = parsed.auth.split(":") if len(split) == 2: username, password = split if parsed.scheme == "socks5": socks_version = socks.PROXY_TYPE_SOCKS5 rdns = False elif parsed.scheme == "socks5h": socks_version = socks.PROXY_TYPE_SOCKS5 rdns = True elif parsed.scheme == "socks4": socks_version = socks.PROXY_TYPE_SOCKS4 rdns = False elif parsed.scheme == "socks4a": socks_version = socks.PROXY_TYPE_SOCKS4 rdns = True else: raise ValueError("Unable to determine SOCKS version from %s" % proxy_url) self.proxy_url = proxy_url socks_options = { "socks_version": socks_version, "proxy_host": parsed.host, "proxy_port": parsed.port, "username": username, "password": password, "rdns": rdns, } connection_pool_kw["_socks_options"] = socks_options super(SOCKSProxyManager, self).__init__( num_pools, headers, **connection_pool_kw ) self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/contrib/socks.py
socks.py
from __future__ import absolute_import import platform from ctypes import ( CDLL, CFUNCTYPE, POINTER, c_bool, c_byte, c_char_p, c_int32, c_long, c_size_t, c_uint32, c_ulong, c_void_p, ) from ctypes.util import find_library from ...packages.six import raise_from if platform.system() != "Darwin": raise ImportError("Only macOS is supported") version = platform.mac_ver()[0] version_info = tuple(map(int, version.split("."))) if version_info < (10, 8): raise OSError( "Only OS X 10.8 and newer are supported, not %s.%s" % (version_info[0], version_info[1]) ) def load_cdll(name, macos10_16_path): """Loads a CDLL by name, falling back to known path on 10.16+""" try: # Big Sur is technically 11 but we use 10.16 due to the Big Sur # beta being labeled as 10.16. if version_info >= (10, 16): path = macos10_16_path else: path = find_library(name) if not path: raise OSError # Caught and reraised as 'ImportError' return CDLL(path, use_errno=True) except OSError: raise_from(ImportError("The library %s failed to load" % name), None) Security = load_cdll( "Security", "/System/Library/Frameworks/Security.framework/Security" ) CoreFoundation = load_cdll( "CoreFoundation", "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", ) Boolean = c_bool CFIndex = c_long CFStringEncoding = c_uint32 CFData = c_void_p CFString = c_void_p CFArray = c_void_p CFMutableArray = c_void_p CFDictionary = c_void_p CFError = c_void_p CFType = c_void_p CFTypeID = c_ulong CFTypeRef = POINTER(CFType) CFAllocatorRef = c_void_p OSStatus = c_int32 CFDataRef = POINTER(CFData) CFStringRef = POINTER(CFString) CFArrayRef = POINTER(CFArray) CFMutableArrayRef = POINTER(CFMutableArray) CFDictionaryRef = POINTER(CFDictionary) CFArrayCallBacks = c_void_p CFDictionaryKeyCallBacks = c_void_p CFDictionaryValueCallBacks = c_void_p SecCertificateRef = POINTER(c_void_p) SecExternalFormat = c_uint32 SecExternalItemType = c_uint32 SecIdentityRef = POINTER(c_void_p) SecItemImportExportFlags = c_uint32 SecItemImportExportKeyParameters = c_void_p SecKeychainRef = POINTER(c_void_p) SSLProtocol = c_uint32 SSLCipherSuite = c_uint32 SSLContextRef = POINTER(c_void_p) SecTrustRef = POINTER(c_void_p) SSLConnectionRef = c_uint32 SecTrustResultType = c_uint32 SecTrustOptionFlags = c_uint32 SSLProtocolSide = c_uint32 SSLConnectionType = c_uint32 SSLSessionOption = c_uint32 try: Security.SecItemImport.argtypes = [ CFDataRef, CFStringRef, POINTER(SecExternalFormat), POINTER(SecExternalItemType), SecItemImportExportFlags, POINTER(SecItemImportExportKeyParameters), SecKeychainRef, POINTER(CFArrayRef), ] Security.SecItemImport.restype = OSStatus Security.SecCertificateGetTypeID.argtypes = [] Security.SecCertificateGetTypeID.restype = CFTypeID Security.SecIdentityGetTypeID.argtypes = [] Security.SecIdentityGetTypeID.restype = CFTypeID Security.SecKeyGetTypeID.argtypes = [] Security.SecKeyGetTypeID.restype = CFTypeID Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef] Security.SecCertificateCreateWithData.restype = SecCertificateRef Security.SecCertificateCopyData.argtypes = [SecCertificateRef] Security.SecCertificateCopyData.restype = CFDataRef Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p] Security.SecCopyErrorMessageString.restype = CFStringRef Security.SecIdentityCreateWithCertificate.argtypes = [ CFTypeRef, SecCertificateRef, POINTER(SecIdentityRef), ] Security.SecIdentityCreateWithCertificate.restype = OSStatus Security.SecKeychainCreate.argtypes = [ c_char_p, c_uint32, c_void_p, Boolean, c_void_p, POINTER(SecKeychainRef), ] Security.SecKeychainCreate.restype = OSStatus Security.SecKeychainDelete.argtypes = [SecKeychainRef] Security.SecKeychainDelete.restype = OSStatus Security.SecPKCS12Import.argtypes = [ CFDataRef, CFDictionaryRef, POINTER(CFArrayRef), ] Security.SecPKCS12Import.restype = OSStatus SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t)) SSLWriteFunc = CFUNCTYPE( OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t) ) Security.SSLSetIOFuncs.argtypes = [SSLContextRef, SSLReadFunc, SSLWriteFunc] Security.SSLSetIOFuncs.restype = OSStatus Security.SSLSetPeerID.argtypes = [SSLContextRef, c_char_p, c_size_t] Security.SSLSetPeerID.restype = OSStatus Security.SSLSetCertificate.argtypes = [SSLContextRef, CFArrayRef] Security.SSLSetCertificate.restype = OSStatus Security.SSLSetCertificateAuthorities.argtypes = [SSLContextRef, CFTypeRef, Boolean] Security.SSLSetCertificateAuthorities.restype = OSStatus Security.SSLSetConnection.argtypes = [SSLContextRef, SSLConnectionRef] Security.SSLSetConnection.restype = OSStatus Security.SSLSetPeerDomainName.argtypes = [SSLContextRef, c_char_p, c_size_t] Security.SSLSetPeerDomainName.restype = OSStatus Security.SSLHandshake.argtypes = [SSLContextRef] Security.SSLHandshake.restype = OSStatus Security.SSLRead.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)] Security.SSLRead.restype = OSStatus Security.SSLWrite.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)] Security.SSLWrite.restype = OSStatus Security.SSLClose.argtypes = [SSLContextRef] Security.SSLClose.restype = OSStatus Security.SSLGetNumberSupportedCiphers.argtypes = [SSLContextRef, POINTER(c_size_t)] Security.SSLGetNumberSupportedCiphers.restype = OSStatus Security.SSLGetSupportedCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), POINTER(c_size_t), ] Security.SSLGetSupportedCiphers.restype = OSStatus Security.SSLSetEnabledCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), c_size_t, ] Security.SSLSetEnabledCiphers.restype = OSStatus Security.SSLGetNumberEnabledCiphers.argtype = [SSLContextRef, POINTER(c_size_t)] Security.SSLGetNumberEnabledCiphers.restype = OSStatus Security.SSLGetEnabledCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), POINTER(c_size_t), ] Security.SSLGetEnabledCiphers.restype = OSStatus Security.SSLGetNegotiatedCipher.argtypes = [SSLContextRef, POINTER(SSLCipherSuite)] Security.SSLGetNegotiatedCipher.restype = OSStatus Security.SSLGetNegotiatedProtocolVersion.argtypes = [ SSLContextRef, POINTER(SSLProtocol), ] Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus Security.SSLCopyPeerTrust.argtypes = [SSLContextRef, POINTER(SecTrustRef)] Security.SSLCopyPeerTrust.restype = OSStatus Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef] Security.SecTrustSetAnchorCertificates.restype = OSStatus Security.SecTrustSetAnchorCertificatesOnly.argstypes = [SecTrustRef, Boolean] Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)] Security.SecTrustEvaluate.restype = OSStatus Security.SecTrustGetCertificateCount.argtypes = [SecTrustRef] Security.SecTrustGetCertificateCount.restype = CFIndex Security.SecTrustGetCertificateAtIndex.argtypes = [SecTrustRef, CFIndex] Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef Security.SSLCreateContext.argtypes = [ CFAllocatorRef, SSLProtocolSide, SSLConnectionType, ] Security.SSLCreateContext.restype = SSLContextRef Security.SSLSetSessionOption.argtypes = [SSLContextRef, SSLSessionOption, Boolean] Security.SSLSetSessionOption.restype = OSStatus Security.SSLSetProtocolVersionMin.argtypes = [SSLContextRef, SSLProtocol] Security.SSLSetProtocolVersionMin.restype = OSStatus Security.SSLSetProtocolVersionMax.argtypes = [SSLContextRef, SSLProtocol] Security.SSLSetProtocolVersionMax.restype = OSStatus try: Security.SSLSetALPNProtocols.argtypes = [SSLContextRef, CFArrayRef] Security.SSLSetALPNProtocols.restype = OSStatus except AttributeError: # Supported only in 10.12+ pass Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p] Security.SecCopyErrorMessageString.restype = CFStringRef Security.SSLReadFunc = SSLReadFunc Security.SSLWriteFunc = SSLWriteFunc Security.SSLContextRef = SSLContextRef Security.SSLProtocol = SSLProtocol Security.SSLCipherSuite = SSLCipherSuite Security.SecIdentityRef = SecIdentityRef Security.SecKeychainRef = SecKeychainRef Security.SecTrustRef = SecTrustRef Security.SecTrustResultType = SecTrustResultType Security.SecExternalFormat = SecExternalFormat Security.OSStatus = OSStatus Security.kSecImportExportPassphrase = CFStringRef.in_dll( Security, "kSecImportExportPassphrase" ) Security.kSecImportItemIdentity = CFStringRef.in_dll( Security, "kSecImportItemIdentity" ) # CoreFoundation time! CoreFoundation.CFRetain.argtypes = [CFTypeRef] CoreFoundation.CFRetain.restype = CFTypeRef CoreFoundation.CFRelease.argtypes = [CFTypeRef] CoreFoundation.CFRelease.restype = None CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef] CoreFoundation.CFGetTypeID.restype = CFTypeID CoreFoundation.CFStringCreateWithCString.argtypes = [ CFAllocatorRef, c_char_p, CFStringEncoding, ] CoreFoundation.CFStringCreateWithCString.restype = CFStringRef CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding] CoreFoundation.CFStringGetCStringPtr.restype = c_char_p CoreFoundation.CFStringGetCString.argtypes = [ CFStringRef, c_char_p, CFIndex, CFStringEncoding, ] CoreFoundation.CFStringGetCString.restype = c_bool CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex] CoreFoundation.CFDataCreate.restype = CFDataRef CoreFoundation.CFDataGetLength.argtypes = [CFDataRef] CoreFoundation.CFDataGetLength.restype = CFIndex CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef] CoreFoundation.CFDataGetBytePtr.restype = c_void_p CoreFoundation.CFDictionaryCreate.argtypes = [ CFAllocatorRef, POINTER(CFTypeRef), POINTER(CFTypeRef), CFIndex, CFDictionaryKeyCallBacks, CFDictionaryValueCallBacks, ] CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef CoreFoundation.CFDictionaryGetValue.argtypes = [CFDictionaryRef, CFTypeRef] CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef CoreFoundation.CFArrayCreate.argtypes = [ CFAllocatorRef, POINTER(CFTypeRef), CFIndex, CFArrayCallBacks, ] CoreFoundation.CFArrayCreate.restype = CFArrayRef CoreFoundation.CFArrayCreateMutable.argtypes = [ CFAllocatorRef, CFIndex, CFArrayCallBacks, ] CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p] CoreFoundation.CFArrayAppendValue.restype = None CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef] CoreFoundation.CFArrayGetCount.restype = CFIndex CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex] CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( CoreFoundation, "kCFAllocatorDefault" ) CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( CoreFoundation, "kCFTypeArrayCallBacks" ) CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll( CoreFoundation, "kCFTypeDictionaryKeyCallBacks" ) CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll( CoreFoundation, "kCFTypeDictionaryValueCallBacks" ) CoreFoundation.CFTypeRef = CFTypeRef CoreFoundation.CFArrayRef = CFArrayRef CoreFoundation.CFStringRef = CFStringRef CoreFoundation.CFDictionaryRef = CFDictionaryRef except (AttributeError): raise ImportError("Error initializing ctypes") class CFConst(object): """ A class object that acts as essentially a namespace for CoreFoundation constants. """ kCFStringEncodingUTF8 = CFStringEncoding(0x08000100) class SecurityConst(object): """ A class object that acts as essentially a namespace for Security constants. """ kSSLSessionOptionBreakOnServerAuth = 0 kSSLProtocol2 = 1 kSSLProtocol3 = 2 kTLSProtocol1 = 4 kTLSProtocol11 = 7 kTLSProtocol12 = 8 # SecureTransport does not support TLS 1.3 even if there's a constant for it kTLSProtocol13 = 10 kTLSProtocolMaxSupported = 999 kSSLClientSide = 1 kSSLStreamType = 0 kSecFormatPEMSequence = 10 kSecTrustResultInvalid = 0 kSecTrustResultProceed = 1 # This gap is present on purpose: this was kSecTrustResultConfirm, which # is deprecated. kSecTrustResultDeny = 3 kSecTrustResultUnspecified = 4 kSecTrustResultRecoverableTrustFailure = 5 kSecTrustResultFatalTrustFailure = 6 kSecTrustResultOtherError = 7 errSSLProtocol = -9800 errSSLWouldBlock = -9803 errSSLClosedGraceful = -9805 errSSLClosedNoNotify = -9816 errSSLClosedAbort = -9806 errSSLXCertChainInvalid = -9807 errSSLCrypto = -9809 errSSLInternal = -9810 errSSLCertExpired = -9814 errSSLCertNotYetValid = -9815 errSSLUnknownRootCert = -9812 errSSLNoRootCert = -9813 errSSLHostNameMismatch = -9843 errSSLPeerHandshakeFail = -9824 errSSLPeerUserCancelled = -9839 errSSLWeakPeerEphemeralDHKey = -9850 errSSLServerAuthCompleted = -9841 errSSLRecordOverflow = -9847 errSecVerifyFailed = -67808 errSecNoTrustSettings = -25263 errSecItemNotFound = -25300 errSecInvalidTrustSettings = -25262 # Cipher suites. We only pick the ones our default cipher string allows. # Source: https://developer.apple.com/documentation/security/1550981-ssl_cipher_suite_values TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014 TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067 TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033 TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035 TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F TLS_AES_128_GCM_SHA256 = 0x1301 TLS_AES_256_GCM_SHA384 = 0x1302 TLS_AES_128_CCM_8_SHA256 = 0x1305 TLS_AES_128_CCM_SHA256 = 0x1304
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/contrib/_securetransport/bindings.py
bindings.py
import base64 import ctypes import itertools import os import re import ssl import struct import tempfile from .bindings import CFConst, CoreFoundation, Security # This regular expression is used to grab PEM data out of a PEM bundle. _PEM_CERTS_RE = re.compile( b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL ) def _cf_data_from_bytes(bytestring): """ Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. """ return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) ) def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ dictionary_size = len(tuples) # We need to get the dictionary keys and values out in the same order. keys = (t[0] for t in tuples) values = (t[1] for t in tuples) cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, ) def _cfstr(py_bstr): """ Given a Python binary data, create a CFString. The string must be CFReleased by the caller. """ c_str = ctypes.c_char_p(py_bstr) cf_str = CoreFoundation.CFStringCreateWithCString( CoreFoundation.kCFAllocatorDefault, c_str, CFConst.kCFStringEncodingUTF8, ) return cf_str def _create_cfstring_array(lst): """ Given a list of Python binary data, create an associated CFMutableArray. The array must be CFReleased by the caller. Raises an ssl.SSLError on failure. """ cf_arr = None try: cf_arr = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) if not cf_arr: raise MemoryError("Unable to allocate memory!") for item in lst: cf_str = _cfstr(item) if not cf_str: raise MemoryError("Unable to allocate memory!") try: CoreFoundation.CFArrayAppendValue(cf_arr, cf_str) finally: CoreFoundation.CFRelease(cf_str) except BaseException as e: if cf_arr: CoreFoundation.CFRelease(cf_arr) raise ssl.SSLError("Unable to allocate array: %s" % (e,)) return cf_arr def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError("Error copying C string from CFStringRef") string = buffer.value if string is not None: string = string.decode("utf-8") return string def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if output is None or output == u"": output = u"OSStatus %s" % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output) def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # Normalize the PEM bundle's line endings. pem_bundle = pem_bundle.replace(b"\r\n", b"\n") der_certs = [ base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle) ] if not der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) raise return cert_array def _is_cert(item): """ Returns True if a given CFTypeRef is a certificate. """ expected = Security.SecCertificateGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _is_identity(item): """ Returns True if a given CFTypeRef is an identity. """ expected = Security.SecIdentityGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # Unfortunately, SecKeychainCreate requires a path to a keychain. This # means we cannot use mkstemp to use a generic temporary file. Instead, # we're going to create a temporary directory and a filename to use there. # This filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b16encode(random_bytes[:8]).decode("utf-8") password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode("utf-8") # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. """ certificates = [] identities = [] result_array = None with open(path, "rb") as f: raw_filedata = f.read() try: filedata = CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata) ) result_array = CoreFoundation.CFArrayRef() result = Security.SecItemImport( filedata, # cert data None, # Filename, leaving it out for now None, # What the type of the file is, we don't care None, # what's in the file, we don't care 0, # import flags None, # key params, can include passphrase in the future keychain, # The keychain to insert into ctypes.byref(result_array), # Results ) _assert_no_error(result) # A CFArray is not very useful to us as an intermediary # representation, so we are going to extract the objects we want # and then free the array. We don't need to keep hold of keys: the # keychain already has them! result_count = CoreFoundation.CFArrayGetCount(result_array) for index in range(result_count): item = CoreFoundation.CFArrayGetValueAtIndex(result_array, index) item = ctypes.cast(item, CoreFoundation.CFTypeRef) if _is_cert(item): CoreFoundation.CFRetain(item) certificates.append(item) elif _is_identity(item): CoreFoundation.CFRetain(item) identities.append(item) finally: if result_array: CoreFoundation.CFRelease(result_array) CoreFoundation.CFRelease(filedata) return (identities, certificates) def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # Ok, the strategy. # # This relies on knowing that macOS will not give you a SecIdentityRef # unless you have imported a key into a keychain. This is a somewhat # artificial limitation of macOS (for example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file(keychain, file_path) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj) TLS_PROTOCOL_VERSIONS = { "SSLv2": (0, 2), "SSLv3": (3, 0), "TLSv1": (3, 1), "TLSv1.1": (3, 2), "TLSv1.2": (3, 3), } def _build_tls_unknown_ca_alert(version): """ Builds a TLS alert record for an unknown CA. """ ver_maj, ver_min = TLS_PROTOCOL_VERSIONS[version] severity_fatal = 0x02 description_unknown_ca = 0x30 msg = struct.pack(">BB", severity_fatal, description_unknown_ca) msg_len = len(msg) record_type_alert = 0x15 record = struct.pack(">BBBH", record_type_alert, ver_maj, ver_min, msg_len) + msg return record
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/contrib/_securetransport/low_level.py
low_level.py
from __future__ import absolute_import import functools import itertools import operator import sys import types __author__ = "Benjamin Peterson <[email protected]>" __version__ = "1.16.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = (str,) integer_types = (int,) class_types = (type,) text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = (basestring,) integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X if PY34: from importlib.util import spec_from_loader else: spec_from_loader = None def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def find_spec(self, fullname, path, target=None): if fullname in self.known_modules: return spec_from_loader(fullname, self) return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code def create_module(self, spec): return self.load_module(spec.name) def exec_module(self, module): pass _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute( "filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse" ), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("getoutput", "commands", "subprocess"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute( "reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload" ), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute( "zip_longest", "itertools", "itertools", "izip_longest", "zip_longest" ), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule( "collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections", ), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"), MovedModule( "_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread", ), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule( "email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart" ), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] # Add windows specific modules. if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute( "unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes" ), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("splitvalue", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module( Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse", ) class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module( Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error", ) class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), MovedAttribute("parse_http_list", "urllib2", "urllib.request"), MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module( Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request", ) class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module( Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response", ) class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = ( _urllib_robotparser_moved_attributes ) _importer._add_module( Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser", ) class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ["parse", "error", "request", "response", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc( get_unbound_function, """Get the function out of a possibly unbound function""" ) get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc( iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary." ) if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO del io _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _assertNotRegex = "assertNotRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" _assertNotRegex = "assertNotRegex" else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r"\\", r"\\\\"), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _assertNotRegex = "assertNotRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) def assertNotRegex(self, *args, **kwargs): return getattr(self, _assertNotRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec ("""exec _code_ in _globs_, _locs_""") exec_( """def reraise(tp, value, tb=None): try: raise tp, value, tb finally: tb = None """ ) if sys.version_info[:2] > (3,): exec_( """def raise_from(value, from_value): try: raise value from from_value finally: value = None """ ) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if ( isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None ): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): # This does exactly the same what the :func:`py3:functools.update_wrapper` # function does on Python versions after 3.2. It sets the ``__wrapped__`` # attribute on ``wrapper`` object and it doesn't raise an error if any of # the attributes mentioned in ``assigned`` and ``updated`` are missing on # ``wrapped`` object. def _update_wrapper( wrapper, wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES, ): for attr in assigned: try: value = getattr(wrapped, attr) except AttributeError: continue else: setattr(wrapper, attr, value) for attr in updated: getattr(wrapper, attr).update(getattr(wrapped, attr, {})) wrapper.__wrapped__ = wrapped return wrapper _update_wrapper.__doc__ = functools.update_wrapper.__doc__ def wraps( wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES, ): return functools.partial( _update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated ) wraps.__doc__ = functools.wraps.__doc__ else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): if sys.version_info[:2] >= (3, 7): # This version introduced PEP 560 that requires a bit # of extra care (we mimic what is done by __build_class__). resolved_bases = types.resolve_bases(bases) if resolved_bases is not bases: d["__orig_bases__"] = bases else: resolved_bases = bases return meta(name, resolved_bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, "temporary_class", (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop("__dict__", None) orig_vars.pop("__weakref__", None) if hasattr(cls, "__qualname__"): orig_vars["__qualname__"] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding="utf-8", errors="strict"): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, binary_type): return s if isinstance(s, text_type): return s.encode(encoding, errors) raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ # Optimization: Fast return for the common case. if type(s) is str: return s if PY2 and isinstance(s, text_type): return s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): return s.decode(encoding, errors) elif not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) return s def ensure_text(s, encoding="utf-8", errors="strict"): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass): """ A class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if "__str__" not in klass.__dict__: raise ValueError( "@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__ ) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode("utf-8") return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if ( type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__ ): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/packages/six.py
six.py
# Note: This file is under the PSF license as the code comes from the python # stdlib. http://docs.python.org/3/license.html import re import sys # ipaddress has been backported to 2.6+ in pypi. If it is installed on the # system, use it to handle IPAddress ServerAltnames (this was added in # python-3.5) otherwise only do DNS matching. This allows # util.ssl_match_hostname to continue to be used in Python 2.7. try: import ipaddress except ImportError: ipaddress = None __version__ = "3.5.0.1" class CertificateError(ValueError): pass def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False # Ported from python3-syntax: # leftmost, *remainder = dn.split(r'.') parts = dn.split(r".") leftmost = parts[0] remainder = parts[1:] wildcards = leftmost.count("*") if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn) ) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == "*": # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append("[^.]+") elif leftmost.startswith("xn--") or hostname.startswith("xn--"): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) return pat.match(hostname) def _to_unicode(obj): if isinstance(obj, str) and sys.version_info < (3,): # ignored flake8 # F821 to support python 2.7 function obj = unicode(obj, encoding="ascii", errors="strict") # noqa: F821 return obj def _ipaddress_match(ipname, host_ip): """Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). """ # OpenSSL may add a trailing newline to a subjectAltName's IP address # Divergence from upstream: ipaddress can't handle byte str ip = ipaddress.ip_address(_to_unicode(ipname).rstrip()) return ip == host_ip def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError( "empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED" ) try: # Divergence from upstream: ipaddress can't handle byte str host_ip = ipaddress.ip_address(_to_unicode(hostname)) except ValueError: # Not an IP address (common case) host_ip = None except UnicodeError: # Divergence from upstream: Have to deal with ipaddress not taking # byte strings. addresses should be all ascii, so we consider it not # an ipaddress in this case host_ip = None except AttributeError: # Divergence from upstream: Make ipaddress library optional if ipaddress is None: host_ip = None else: raise dnsnames = [] san = cert.get("subjectAltName", ()) for key, value in san: if key == "DNS": if host_ip is None and _dnsname_match(value, hostname): return dnsnames.append(value) elif key == "IP Address": if host_ip is not None and _ipaddress_match(value, host_ip): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get("subject", ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == "commonName": if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError( "hostname %r " "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) ) elif len(dnsnames) == 1: raise CertificateError("hostname %r doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError( "no appropriate commonName or subjectAltName fields were found" )
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/ssl_match_hostname.py
ssl_match_hostname.py
from __future__ import absolute_import from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect from ..exceptions import HeaderParsingError from ..packages.six.moves import http_client as httplib def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ try: # Check `isclosed()` first, in case Python3 doesn't set `closed`. # GH Issue #928 return obj.isclosed() except AttributeError: pass try: # Check via the official file-like-object way. return obj.closed except AttributeError: pass try: # Check if the object is a container for another file-like object that # gets released on exhaustion (e.g. HTTPResponse). return obj.fp is None except AttributeError: pass raise ValueError("Unable to determine whether fp is closed.") def assert_header_parsing(headers): """ Asserts whether all headers have been successfully parsed. Extracts encountered errors from the result of parsing headers. Only works on Python 3. :param http.client.HTTPMessage headers: Headers to verify. :raises urllib3.exceptions.HeaderParsingError: If parsing errors are found. """ # This will fail silently if we pass in the wrong kind of parameter. # To make debugging easier add an explicit check. if not isinstance(headers, httplib.HTTPMessage): raise TypeError("expected httplib.Message, got {0}.".format(type(headers))) defects = getattr(headers, "defects", None) get_payload = getattr(headers, "get_payload", None) unparsed_data = None if get_payload: # get_payload is actually email.message.Message.get_payload; # we're only interested in the result if it's not a multipart message if not headers.is_multipart(): payload = get_payload() if isinstance(payload, (bytes, str)): unparsed_data = payload if defects: # httplib is assuming a response body is available # when parsing headers even when httplib only sends # header data to parse_headers() This results in # defects on multipart responses in particular. # See: https://github.com/urllib3/urllib3/issues/800 # So we ignore the following defects: # - StartBoundaryNotFoundDefect: # The claimed start boundary was never found. # - MultipartInvariantViolationDefect: # A message claimed to be a multipart but no subparts were found. defects = [ defect for defect in defects if not isinstance( defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) ) ] if defects or unparsed_data: raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) def is_response_to_head(response): """ Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine. :param http.client.HTTPResponse response: Response to check if the originating request used 'HEAD' as a method. """ # FIXME: Can we do this somehow without accessing private httplib _method? method = response._method if isinstance(method, int): # Platform-specific: Appengine return method == 3 return method.upper() == "HEAD"
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/response.py
response.py
import io import socket import ssl from ..exceptions import ProxySchemeUnsupported from ..packages import six SSL_BLOCKSIZE = 16384 class SSLTransport: """ The SSLTransport wraps an existing socket and establishes an SSL connection. Contrary to Python's implementation of SSLSocket, it allows you to chain multiple TLS connections together. It's particularly useful if you need to implement TLS within TLS. The class supports most of the socket API operations. """ @staticmethod def _validate_ssl_context_for_tls_in_tls(ssl_context): """ Raises a ProxySchemeUnsupported if the provided ssl_context can't be used for TLS in TLS. The only requirement is that the ssl_context provides the 'wrap_bio' methods. """ if not hasattr(ssl_context, "wrap_bio"): if six.PY2: raise ProxySchemeUnsupported( "TLS in TLS requires SSLContext.wrap_bio() which isn't " "supported on Python 2" ) else: raise ProxySchemeUnsupported( "TLS in TLS requires SSLContext.wrap_bio() which isn't " "available on non-native SSLContext" ) def __init__( self, socket, ssl_context, server_hostname=None, suppress_ragged_eofs=True ): """ Create an SSLTransport around socket using the provided ssl_context. """ self.incoming = ssl.MemoryBIO() self.outgoing = ssl.MemoryBIO() self.suppress_ragged_eofs = suppress_ragged_eofs self.socket = socket self.sslobj = ssl_context.wrap_bio( self.incoming, self.outgoing, server_hostname=server_hostname ) # Perform initial handshake. self._ssl_io_loop(self.sslobj.do_handshake) def __enter__(self): return self def __exit__(self, *_): self.close() def fileno(self): return self.socket.fileno() def read(self, len=1024, buffer=None): return self._wrap_ssl_read(len, buffer) def recv(self, len=1024, flags=0): if flags != 0: raise ValueError("non-zero flags not allowed in calls to recv") return self._wrap_ssl_read(len) def recv_into(self, buffer, nbytes=None, flags=0): if flags != 0: raise ValueError("non-zero flags not allowed in calls to recv_into") if buffer and (nbytes is None): nbytes = len(buffer) elif nbytes is None: nbytes = 1024 return self.read(nbytes, buffer) def sendall(self, data, flags=0): if flags != 0: raise ValueError("non-zero flags not allowed in calls to sendall") count = 0 with memoryview(data) as view, view.cast("B") as byte_view: amount = len(byte_view) while count < amount: v = self.send(byte_view[count:]) count += v def send(self, data, flags=0): if flags != 0: raise ValueError("non-zero flags not allowed in calls to send") response = self._ssl_io_loop(self.sslobj.write, data) return response def makefile( self, mode="r", buffering=None, encoding=None, errors=None, newline=None ): """ Python's httpclient uses makefile and buffered io when reading HTTP messages and we need to support it. This is unfortunately a copy and paste of socket.py makefile with small changes to point to the socket directly. """ if not set(mode) <= {"r", "w", "b"}: raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) writing = "w" in mode reading = "r" in mode or not writing assert reading or writing binary = "b" in mode rawmode = "" if reading: rawmode += "r" if writing: rawmode += "w" raw = socket.SocketIO(self, rawmode) self.socket._io_refs += 1 if buffering is None: buffering = -1 if buffering < 0: buffering = io.DEFAULT_BUFFER_SIZE if buffering == 0: if not binary: raise ValueError("unbuffered streams must be binary") return raw if reading and writing: buffer = io.BufferedRWPair(raw, raw, buffering) elif reading: buffer = io.BufferedReader(raw, buffering) else: assert writing buffer = io.BufferedWriter(raw, buffering) if binary: return buffer text = io.TextIOWrapper(buffer, encoding, errors, newline) text.mode = mode return text def unwrap(self): self._ssl_io_loop(self.sslobj.unwrap) def close(self): self.socket.close() def getpeercert(self, binary_form=False): return self.sslobj.getpeercert(binary_form) def version(self): return self.sslobj.version() def cipher(self): return self.sslobj.cipher() def selected_alpn_protocol(self): return self.sslobj.selected_alpn_protocol() def selected_npn_protocol(self): return self.sslobj.selected_npn_protocol() def shared_ciphers(self): return self.sslobj.shared_ciphers() def compression(self): return self.sslobj.compression() def settimeout(self, value): self.socket.settimeout(value) def gettimeout(self): return self.socket.gettimeout() def _decref_socketios(self): self.socket._decref_socketios() def _wrap_ssl_read(self, len, buffer=None): try: return self._ssl_io_loop(self.sslobj.read, len, buffer) except ssl.SSLError as e: if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs: return 0 # eof, return 0. else: raise def _ssl_io_loop(self, func, *args): """Performs an I/O loop between incoming/outgoing and the socket.""" should_loop = True ret = None while should_loop: errno = None try: ret = func(*args) except ssl.SSLError as e: if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): # WANT_READ, and WANT_WRITE are expected, others are not. raise e errno = e.errno buf = self.outgoing.read() self.socket.sendall(buf) if errno is None: should_loop = False elif errno == ssl.SSL_ERROR_WANT_READ: buf = self.socket.recv(SSL_BLOCKSIZE) if buf: self.incoming.write(buf) else: self.incoming.write_eof() return ret
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/ssltransport.py
ssltransport.py
from __future__ import absolute_import import socket from ..contrib import _appengine_environ from ..exceptions import LocationParseError from ..packages import six from .wait import NoWayToWaitForSocketError, wait_for_read def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`http.client.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, "sock", False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True try: # Returns True if readable, which here means it's been dropped return wait_for_read(sock, timeout=0.0) except NoWayToWaitForSocketError: # Platform-specific: AppEngine return False # This function is copied from socket.py in the Python 2.7 standard # library test suite. Added to its signature is only `socket_options`. # One additional modification is that we avoid binding to IPv6 servers # discovered in DNS if the system doesn't have IPv6 functionality. def create_connection( address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None, ): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`socket.getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith("["): host = host.strip("[]") err = None # Using the value from allowed_gai_family() in the context of getaddrinfo lets # us select whether to work with IPv4 DNS records, IPv6 records, or both. # The original create_connection function always returns all records. family = allowed_gai_family() try: host.encode("idna") except UnicodeError: return six.raise_from( LocationParseError(u"'%s', label empty or too long" % host), None ) for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list") def _set_socket_options(sock, options): if options is None: return for opt in options: sock.setsockopt(*opt) def allowed_gai_family(): """This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.""" family = socket.AF_INET if HAS_IPV6: family = socket.AF_UNSPEC return family def _has_ipv6(host): """Returns True if the system can bind an IPv6 address.""" sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/urllib3/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6 HAS_IPV6 = _has_ipv6("::1")
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/connection.py
connection.py
import errno import select import sys from functools import partial try: from time import monotonic except ImportError: from time import time as monotonic __all__ = ["NoWayToWaitForSocketError", "wait_for_read", "wait_for_write"] class NoWayToWaitForSocketError(Exception): pass # How should we wait on sockets? # # There are two types of APIs you can use for waiting on sockets: the fancy # modern stateful APIs like epoll/kqueue, and the older stateless APIs like # select/poll. The stateful APIs are more efficient when you have a lots of # sockets to keep track of, because you can set them up once and then use them # lots of times. But we only ever want to wait on a single socket at a time # and don't want to keep track of state, so the stateless APIs are actually # more efficient. So we want to use select() or poll(). # # Now, how do we choose between select() and poll()? On traditional Unixes, # select() has a strange calling convention that makes it slow, or fail # altogether, for high-numbered file descriptors. The point of poll() is to fix # that, so on Unixes, we prefer poll(). # # On Windows, there is no poll() (or at least Python doesn't provide a wrapper # for it), but that's OK, because on Windows, select() doesn't have this # strange calling convention; plain select() works fine. # # So: on Windows we use select(), and everywhere else we use poll(). We also # fall back to select() in case poll() is somehow broken or missing. if sys.version_info >= (3, 5): # Modern Python, that retries syscalls by default def _retry_on_intr(fn, timeout): return fn(timeout) else: # Old and broken Pythons. def _retry_on_intr(fn, timeout): if timeout is None: deadline = float("inf") else: deadline = monotonic() + timeout while True: try: return fn(timeout) # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7 except (OSError, select.error) as e: # 'e.args[0]' incantation works for both OSError and select.error if e.args[0] != errno.EINTR: raise else: timeout = deadline - monotonic() if timeout < 0: timeout = 0 if timeout == float("inf"): timeout = None continue def select_wait_for_socket(sock, read=False, write=False, timeout=None): if not read and not write: raise RuntimeError("must specify at least one of read=True, write=True") rcheck = [] wcheck = [] if read: rcheck.append(sock) if write: wcheck.append(sock) # When doing a non-blocking connect, most systems signal success by # marking the socket writable. Windows, though, signals success by marked # it as "exceptional". We paper over the difference by checking the write # sockets for both conditions. (The stdlib selectors module does the same # thing.) fn = partial(select.select, rcheck, wcheck, wcheck) rready, wready, xready = _retry_on_intr(fn, timeout) return bool(rready or wready or xready) def poll_wait_for_socket(sock, read=False, write=False, timeout=None): if not read and not write: raise RuntimeError("must specify at least one of read=True, write=True") mask = 0 if read: mask |= select.POLLIN if write: mask |= select.POLLOUT poll_obj = select.poll() poll_obj.register(sock, mask) # For some reason, poll() takes timeout in milliseconds def do_poll(t): if t is not None: t *= 1000 return poll_obj.poll(t) return bool(_retry_on_intr(do_poll, timeout)) def null_wait_for_socket(*args, **kwargs): raise NoWayToWaitForSocketError("no select-equivalent available") def _have_working_poll(): # Apparently some systems have a select.poll that fails as soon as you try # to use it, either due to strange configuration or broken monkeypatching # from libraries like eventlet/greenlet. try: poll_obj = select.poll() _retry_on_intr(poll_obj.poll, 0) except (AttributeError, OSError): return False else: return True def wait_for_socket(*args, **kwargs): # We delay choosing which implementation to use until the first time we're # called. We could do it at import time, but then we might make the wrong # decision if someone goes wild with monkeypatching select.poll after # we're imported. global wait_for_socket if _have_working_poll(): wait_for_socket = poll_wait_for_socket elif hasattr(select, "select"): wait_for_socket = select_wait_for_socket else: # Platform-specific: Appengine. wait_for_socket = null_wait_for_socket return wait_for_socket(*args, **kwargs) def wait_for_read(sock, timeout=None): """Waits for reading to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired. """ return wait_for_socket(sock, read=True, timeout=timeout) def wait_for_write(sock, timeout=None): """Waits for writing to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired. """ return wait_for_socket(sock, write=True, timeout=timeout)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/wait.py
wait.py
from __future__ import absolute_import import hmac import os import sys import warnings from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import ( InsecurePlatformWarning, ProxySchemeUnsupported, SNIMissingWarning, SSLError, ) from ..packages import six from .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE SSLContext = None SSLTransport = None HAS_SNI = False IS_PYOPENSSL = False IS_SECURETRANSPORT = False ALPN_PROTOCOLS = ["http/1.1"] # Maps the length of a digest to a possible hash function producing this digest HASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256} def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. """ result = abs(len(a) - len(b)) for left, right in zip(bytearray(a), bytearray(b)): result |= left ^ right return result == 0 _const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport) try: # Test for SSL features import ssl from ssl import CERT_REQUIRED, wrap_socket except ImportError: pass try: from ssl import HAS_SNI # Has SNI? except ImportError: pass try: from .ssltransport import SSLTransport except ImportError: pass try: # Platform-specific: Python 3.6 from ssl import PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: try: from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 try: from ssl import PROTOCOL_TLS_CLIENT except ImportError: PROTOCOL_TLS_CLIENT = PROTOCOL_TLS try: from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3 except ImportError: OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000 OP_NO_COMPRESSION = 0x20000 try: # OP_NO_TICKET was added in Python 3.6 from ssl import OP_NO_TICKET except ImportError: OP_NO_TICKET = 0x4000 # A secure default. # Sources for more information on TLS ciphers: # # - https://wiki.mozilla.org/Security/Server_Side_TLS # - https://www.ssllabs.com/projects/best-practices/index.html # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/ # # The general intent is: # - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE), # - prefer ECDHE over DHE for better performance, # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and # security, # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common, # - disable NULL authentication, MD5 MACs, DSS, and other # insecure ciphers for security reasons. # - NOTE: TLS 1.3 cipher suites are managed through a different interface # not exposed by CPython (yet!) and are enabled by default if they're available. DEFAULT_CIPHERS = ":".join( [ "ECDHE+AESGCM", "ECDHE+CHACHA20", "DHE+AESGCM", "DHE+CHACHA20", "ECDH+AESGCM", "DH+AESGCM", "ECDH+AES", "DH+AES", "RSA+AESGCM", "RSA+AES", "!aNULL", "!eNULL", "!MD5", "!DSS", ] ) try: from ssl import SSLContext # Modern SSL? except ImportError: class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version # Use default values from a real SSLContext self.check_hostname = False self.verify_mode = ssl.CERT_NONE self.ca_certs = None self.options = 0 self.certfile = None self.keyfile = None self.ciphers = None def load_cert_chain(self, certfile, keyfile): self.certfile = certfile self.keyfile = keyfile def load_verify_locations(self, cafile=None, capath=None, cadata=None): self.ca_certs = cafile if capath is not None: raise SSLError("CA directories not supported in older Pythons") if cadata is not None: raise SSLError("CA data not supported in older Pythons") def set_ciphers(self, cipher_suite): self.ciphers = cipher_suite def wrap_socket(self, socket, server_hostname=None, server_side=False): warnings.warn( "A true SSLContext object is not available. This prevents " "urllib3 from configuring SSL appropriately and may cause " "certain SSL connections to fail. You can upgrade to a newer " "version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#ssl-warnings", InsecurePlatformWarning, ) kwargs = { "keyfile": self.keyfile, "certfile": self.certfile, "ca_certs": self.ca_certs, "cert_reqs": self.verify_mode, "ssl_version": self.protocol, "server_side": server_side, } return wrap_socket(socket, ciphers=self.ciphers, **kwargs) def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(":", "").lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError( 'Fingerprints did not match. Expected "{0}", got "{1}".'.format( fingerprint, hexlify(cert_digest) ) ) def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_REQUIRED`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbreviation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. """ if candidate is None: return CERT_REQUIRED if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, "CERT_" + candidate) return res return candidate def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_TLS if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, "PROTOCOL_" + candidate) return res return candidate def create_urllib3_context( ssl_version=None, cert_reqs=None, options=None, ciphers=None ): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ # PROTOCOL_TLS is deprecated in Python 3.10 if not ssl_version or ssl_version == PROTOCOL_TLS: ssl_version = PROTOCOL_TLS_CLIENT context = SSLContext(ssl_version) context.set_ciphers(ciphers or DEFAULT_CIPHERS) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION # TLSv1.2 only. Unless set explicitly, do not request tickets. # This may save some bandwidth on wire, and although the ticket is encrypted, # there is a risk associated with it being on wire, # if the server is not rotating its ticketing keys properly. options |= OP_NO_TICKET context.options |= options # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is # necessary for conditional client cert authentication with TLS 1.3. # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older # versions of Python. We only enable on Python 3.7.4+ or if certificate # verification is enabled to work around Python issue #37428 # See: https://bugs.python.org/issue37428 if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr( context, "post_handshake_auth", None ) is not None: context.post_handshake_auth = True def disable_check_hostname(): if ( getattr(context, "check_hostname", None) is not None ): # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False # The order of the below lines setting verify_mode and check_hostname # matter due to safe-guards SSLContext has to prevent an SSLContext with # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used # or not so we don't know the initial state of the freshly created SSLContext. if cert_reqs == ssl.CERT_REQUIRED: context.verify_mode = cert_reqs disable_check_hostname() else: disable_check_hostname() context.verify_mode = cert_reqs # Enable logging of TLS session keys via defacto standard environment variable # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values. if hasattr(context, "keylog_filename"): sslkeylogfile = os.environ.get("SSLKEYLOGFILE") if sslkeylogfile: context.keylog_filename = sslkeylogfile return context def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ca_cert_data=None, tls_in_tls=False, ): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket. """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir or ca_cert_data: try: context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) except (IOError, OSError) as e: raise SSLError(e) elif ssl_context is None and hasattr(context, "load_default_certs"): # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() # Attempt to detect if we get the goofy behavior of the # keyfile being encrypted and OpenSSL asking for the # passphrase via the terminal and instead error out. if keyfile and key_password is None and _is_key_file_encrypted(keyfile): raise SSLError("Client private key is encrypted, password is required") if certfile: if key_password is None: context.load_cert_chain(certfile, keyfile) else: context.load_cert_chain(certfile, keyfile, key_password) try: if hasattr(context, "set_alpn_protocols"): context.set_alpn_protocols(ALPN_PROTOCOLS) except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols pass # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 use_sni_hostname = server_hostname and not is_ipaddress(server_hostname) # SecureTransport uses server_hostname in certificate verification. send_sni = (use_sni_hostname and HAS_SNI) or ( IS_SECURETRANSPORT and server_hostname ) # Do not warn the user if server_hostname is an invalid SNI hostname. if not HAS_SNI and use_sni_hostname: warnings.warn( "An HTTPS request has been made, but the SNI (Server Name " "Indication) extension to TLS is not available on this platform. " "This may cause the server to present an incorrect TLS " "certificate, which can cause validation failures. You can upgrade to " "a newer version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#ssl-warnings", SNIMissingWarning, ) if send_sni: ssl_sock = _ssl_wrap_socket_impl( sock, context, tls_in_tls, server_hostname=server_hostname ) else: ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls) return ssl_sock def is_ipaddress(hostname): """Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise. """ if not six.PY2 and isinstance(hostname, bytes): # IDN A-label bytes are ASCII compatible. hostname = hostname.decode("ascii") return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname)) def _is_key_file_encrypted(key_file): """Detects if a key file is encrypted or not.""" with open(key_file, "r") as f: for line in f: # Look for Proc-Type: 4,ENCRYPTED if "ENCRYPTED" in line: return True return False def _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None): if tls_in_tls: if not SSLTransport: # Import error, ssl is not available. raise ProxySchemeUnsupported( "TLS in TLS requires support for the 'ssl' module" ) SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) return SSLTransport(sock, ssl_context, server_hostname) if server_hostname: return ssl_context.wrap_socket(sock, server_hostname=server_hostname) else: return ssl_context.wrap_socket(sock)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/ssl_.py
ssl_.py
from __future__ import absolute_import import re from collections import namedtuple from ..exceptions import LocationParseError from ..packages import six url_attrs = ["scheme", "auth", "host", "port", "path", "query", "fragment"] # We only want to normalize urls with an HTTP(S) scheme. # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ("http", "https", None) # Almost all of these patterns were derived from the # 'rfc3986' module: https://github.com/python-hyper/rfc3986 PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}") SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)") URI_RE = re.compile( r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" r"(?://([^\\/?#]*))?" r"([^?#]*)" r"(?:\?([^#]*))?" r"(?:#(.*))?$", re.UNICODE | re.DOTALL, ) IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}" HEX_PAT = "[0-9A-Fa-f]{1,4}" LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=HEX_PAT, ipv4=IPV4_PAT) _subs = {"hex": HEX_PAT, "ls32": LS32_PAT} _variations = [ # 6( h16 ":" ) ls32 "(?:%(hex)s:){6}%(ls32)s", # "::" 5( h16 ":" ) ls32 "::(?:%(hex)s:){5}%(ls32)s", # [ h16 ] "::" 4( h16 ":" ) ls32 "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", # [ *4( h16 ":" ) h16 ] "::" ls32 "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", # [ *5( h16 ":" ) h16 ] "::" h16 "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", # [ *6( h16 ":" ) h16 ] "::" "(?:(?:%(hex)s:){0,6}%(hex)s)?::", ] UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._!\-~" IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")" ZONE_ID_PAT = "(?:%25|%)(?:[" + UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+" IPV6_ADDRZ_PAT = r"\[" + IPV6_PAT + r"(?:" + ZONE_ID_PAT + r")?\]" REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*" TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") IPV4_RE = re.compile("^" + IPV4_PAT + "$") IPV6_RE = re.compile("^" + IPV6_PAT + "$") IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT + "$") BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT[2:-2] + "$") ZONE_ID_RE = re.compile("(" + ZONE_ID_PAT + r")\]$") _HOST_PORT_PAT = ("^(%s|%s|%s)(?::([0-9]{0,5}))?$") % ( REG_NAME_PAT, IPV4_PAT, IPV6_ADDRZ_PAT, ) _HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL) UNRESERVED_CHARS = set( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" ) SUB_DELIM_CHARS = set("!$&'()*+,;=") USERINFO_CHARS = UNRESERVED_CHARS | SUB_DELIM_CHARS | {":"} PATH_CHARS = USERINFO_CHARS | {"@", "/"} QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {"?"} class Url(namedtuple("Url", url_attrs)): """ Data structure for representing an HTTP URL. Used as a return value for :func:`parse_url`. Both the scheme and host are normalized as they are both case-insensitive according to RFC 3986. """ __slots__ = () def __new__( cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None, ): if path and not path.startswith("/"): path = "/" + path if scheme is not None: scheme = scheme.lower() return super(Url, cls).__new__( cls, scheme, auth, host, port, path, query, fragment ) @property def hostname(self): """For backwards-compatibility with urlparse. We're nice like that.""" return self.host @property def request_uri(self): """Absolute path including the query string.""" uri = self.path or "/" if self.query is not None: uri += "?" + self.query return uri @property def netloc(self): """Network location including host and port""" if self.port: return "%s:%d" % (self.host, self.port) return self.host @property def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:[email protected]:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = u"" # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + u"://" if auth is not None: url += auth + u"@" if host is not None: url += host if port is not None: url += u":" + str(port) if path is not None: url += path if query is not None: url += u"?" + query if fragment is not None: url += u"#" + fragment return url def __str__(self): return self.url def split_first(s, delims): """ .. deprecated:: 1.25 Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims. """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, "", None return s[:min_idx], s[min_idx + 1 :], min_delim 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) # Normalize existing percent-encoded bytes. # Try to see if the component we're encoding is already percent-encoded # so we can skip all '%' characters but still encode all others. component, percent_encodings = PERCENT_RE.subn( lambda match: match.group(0).upper(), component ) uri_bytes = component.encode("utf-8", "surrogatepass") is_percent_encoded = 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 += byte continue encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) return encoded_component.decode(encoding) def _remove_path_dot_segments(path): # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code segments = path.split("/") # Turn the path into a list of segments output = [] # Initialize the variable to use to store output for segment in segments: # '.' is the current directory, so ignore it, it is superfluous if segment == ".": continue # Anything other than '..', should be appended to the output elif segment != "..": output.append(segment) # In this case segment == '..', if we can, we should pop the last # element elif output: output.pop() # If the path starts with '/' and the output is empty or the first string # is non-empty if path.startswith("/") and (not output or output[0]): output.insert(0, "") # If the path starts with '/.' or '/..' ensure we add one more empty # string to add a trailing '/' if path.endswith(("/.", "/..")): output.append("") return "/".join(output) def _normalize_host(host, scheme): if host: if isinstance(host, six.binary_type): host = six.ensure_str(host) if scheme in NORMALIZABLE_SCHEMES: is_ipv6 = IPV6_ADDRZ_RE.match(host) if is_ipv6: match = ZONE_ID_RE.search(host) if match: start, end = match.span(1) zone_id = host[start:end] if zone_id.startswith("%25") and zone_id != "%25": zone_id = zone_id[3:] else: zone_id = zone_id[1:] zone_id = "%" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS) return host[:start].lower() + zone_id + host[end:] else: return host.lower() elif not IPV4_RE.match(host): return six.ensure_str( b".".join([_idna_encode(label) for label in host.split(".")]) ) return host 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") def _encode_target(target): """Percent-encodes a request target so that there are no invalid characters""" path, query = TARGET_RE.match(target).groups() target = _encode_invalid_chars(path, PATH_CHARS) query = _encode_invalid_chars(query, QUERY_CHARS) if query is not None: target += "?" + query return target def parse_url(url): """ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. This parser is RFC 3986 compliant. The parser logic and helper functions are based heavily on work done in the ``rfc3986`` module. :param str url: URL to parse into a :class:`.Url` namedtuple. Partly backwards-compatible with :mod:`urlparse`. Example:: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/mail/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) """ if not url: # Empty return Url() source_url = url if not SCHEME_RE.search(url): url = "//" + url try: scheme, authority, path, query, fragment = URI_RE.match(url).groups() normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES if scheme: scheme = scheme.lower() if authority: auth, _, host_port = authority.rpartition("@") auth = auth or None host, port = _HOST_PORT_RE.match(host_port).groups() if auth and normalize_uri: auth = _encode_invalid_chars(auth, USERINFO_CHARS) if port == "": port = None else: auth, host, port = None, None, None if port is not None: port = int(port) if not (0 <= port <= 65535): raise LocationParseError(url) host = _normalize_host(host, scheme) if normalize_uri and path: path = _remove_path_dot_segments(path) path = _encode_invalid_chars(path, PATH_CHARS) if normalize_uri and query: query = _encode_invalid_chars(query, QUERY_CHARS) if normalize_uri and fragment: fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS) except (ValueError, AttributeError): return six.raise_from(LocationParseError(source_url), None) # For the sake of backwards compatibility we put empty # string values for path if there are any defined values # beyond the path in the URL. # TODO: Remove this when we break backwards compatibility. if not path: if query is not None or fragment is not None: path = "" else: path = None # Ensure that each part of the URL is a `str` for # backwards compatibility. if isinstance(url, six.text_type): ensure_func = six.ensure_text else: ensure_func = six.ensure_str def ensure_type(x): return x if x is None else ensure_func(x) return Url( scheme=ensure_type(scheme), auth=ensure_type(auth), host=ensure_type(host), port=port, path=ensure_type(path), query=ensure_type(query), fragment=ensure_type(fragment), ) def get_host(url): """ Deprecated. Use :func:`parse_url` instead. """ p = parse_url(url) return p.scheme or "http", p.hostname, p.port
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/url.py
url.py
from __future__ import absolute_import from base64 import b64encode from ..exceptions import UnrewindableBodyError from ..packages.six import b, integer_types # Pass as a value within ``headers`` to skip # emitting some HTTP headers that are added automatically. # The only headers that are supported are ``Accept-Encoding``, # ``Host``, and ``User-Agent``. SKIP_HEADER = "@@@SKIP_HEADER@@@" SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"]) ACCEPT_ENCODING = "gzip,deflate" try: import brotli as _unused_module_brotli # noqa: F401 except ImportError: pass else: ACCEPT_ENCODING += ",br" _FAILEDTELL = object() def make_headers( keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None, ): """ Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} """ headers = {} if accept_encoding: if isinstance(accept_encoding, str): pass elif isinstance(accept_encoding, list): accept_encoding = ",".join(accept_encoding) else: accept_encoding = ACCEPT_ENCODING headers["accept-encoding"] = accept_encoding if user_agent: headers["user-agent"] = user_agent if keep_alive: headers["connection"] = "keep-alive" if basic_auth: headers["authorization"] = "Basic " + b64encode(b(basic_auth)).decode("utf-8") if proxy_basic_auth: headers["proxy-authorization"] = "Basic " + b64encode( b(proxy_basic_auth) ).decode("utf-8") if disable_cache: headers["cache-control"] = "no-cache" return headers def set_file_position(body, pos): """ If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. """ if pos is not None: rewind_body(body, pos) elif getattr(body, "tell", None) is not None: try: pos = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body. pos = _FAILEDTELL return pos def rewind_body(body, body_pos): """ Attempt to rewind body to a certain position. Primarily used for request redirects and retries. :param body: File-like object that supports seek. :param int pos: Position to seek to in file. """ body_seek = getattr(body, "seek", None) if body_seek is not None and isinstance(body_pos, integer_types): try: body_seek(body_pos) except (IOError, OSError): raise UnrewindableBodyError( "An error occurred when rewinding request body for redirect/retry." ) elif body_pos is _FAILEDTELL: raise UnrewindableBodyError( "Unable to record file position for rewinding " "request body during a redirect/retry." ) else: raise ValueError( "body_pos must be of type integer, instead it was %s." % type(body_pos) )
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/request.py
request.py
from __future__ import absolute_import import time # The default socket timeout, used by httplib to indicate that no timeout was # specified by the user from socket import _GLOBAL_DEFAULT_TIMEOUT from ..exceptions import TimeoutStateError # A sentinel value to indicate that no timeout was specified by the user in # urllib3 _Default = object() # Use time.monotonic if available. current_time = getattr(time, "monotonic", time.time) class Timeout(object): """Timeout configuration. Timeouts can be defined as a default for a pool: .. code-block:: python timeout = Timeout(connect=2.0, read=7.0) http = PoolManager(timeout=timeout) response = http.request('GET', 'http://example.com/') Or per-request (which overrides the default for the pool): .. code-block:: python response = http.request('GET', 'http://example.com/', timeout=Timeout(10)) Timeouts can be disabled by setting all the parameters to ``None``: .. code-block:: python no_timeout = Timeout(connect=None, read=None) response = http.request('GET', 'http://example.com/, timeout=no_timeout) :param total: This combines the connect and read timeouts into one; the read timeout will be set to the time leftover from the connect attempt. In the event that both a connect timeout and a total are specified, or a read timeout and a total are specified, the shorter timeout will be applied. Defaults to None. :type total: int, float, or None :param connect: The maximum amount of time (in seconds) to wait for a connection attempt to a server to succeed. Omitting the parameter will default the connect timeout to the system default, probably `the global default timeout in socket.py <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_. None will set an infinite timeout for connection attempts. :type connect: int, float, or None :param read: The maximum amount of time (in seconds) to wait between consecutive read operations for a response from the server. Omitting the parameter will default the read timeout to the system default, probably `the global default timeout in socket.py <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_. None will set an infinite timeout. :type read: int, float, or None .. note:: Many factors can affect the total amount of time for urllib3 to return an HTTP response. For example, Python's DNS resolver does not obey the timeout specified on the socket. Other factors that can affect total request time include high CPU load, high swap, the program running at a low priority level, or other behaviors. In addition, the read and total timeouts only measure the time between read operations on the socket connecting the client and the server, not the total amount of time for the request to return a complete response. For most requests, the timeout is raised because the server has not sent the first byte in the specified time. This is not always the case; if a server streams one byte every fifteen seconds, a timeout of 20 seconds will not trigger, even though the request will take several minutes to complete. If your goal is to cut off any request after a set amount of wall clock time, consider having a second "watcher" thread to cut off a slow request. """ #: A sentinel object representing the default timeout value DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT def __init__(self, total=None, connect=_Default, read=_Default): self._connect = self._validate_timeout(connect, "connect") self._read = self._validate_timeout(read, "read") self.total = self._validate_timeout(total, "total") self._start_connect = None def __repr__(self): return "%s(connect=%r, read=%r, total=%r)" % ( type(self).__name__, self._connect, self._read, self.total, ) # __str__ provided for backwards compatibility __str__ = __repr__ @classmethod def _validate_timeout(cls, value, name): """Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it is a numeric value less than or equal to zero, or the type is not an integer, float, or None. """ if value is _Default: return cls.DEFAULT_TIMEOUT if value is None or value is cls.DEFAULT_TIMEOUT: return value if isinstance(value, bool): raise ValueError( "Timeout cannot be a boolean value. It must " "be an int, float or None." ) try: float(value) except (TypeError, ValueError): raise ValueError( "Timeout value %s was %s, but it must be an " "int, float or None." % (name, value) ) try: if value <= 0: raise ValueError( "Attempted to set %s timeout to %s, but the " "timeout cannot be set to a value less " "than or equal to 0." % (name, value) ) except TypeError: # Python 3 raise ValueError( "Timeout value %s was %s, but it must be an " "int, float or None." % (name, value) ) return value @classmethod def from_float(cls, timeout): """Create a new Timeout from a legacy timeout value. The timeout value used by httplib.py sets the same timeout on the connect(), and recv() socket requests. This creates a :class:`Timeout` object that sets the individual timeouts to the ``timeout`` value passed to this function. :param timeout: The legacy timeout value. :type timeout: integer, float, sentinel default object, or None :return: Timeout object :rtype: :class:`Timeout` """ return Timeout(read=timeout, connect=timeout) def clone(self): """Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` """ # We can't use copy.deepcopy because that will also create a new object # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to # detect the user default. return Timeout(connect=self._connect, read=self._read, total=self.total) def start_connect(self): """Start the timeout clock, used during a connect() attempt :raises urllib3.exceptions.TimeoutStateError: if you attempt to start a timer that has been started already. """ if self._start_connect is not None: raise TimeoutStateError("Timeout timer has already been started.") self._start_connect = current_time() return self._start_connect def get_connect_duration(self): """Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time in seconds. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started. """ if self._start_connect is None: raise TimeoutStateError( "Can't get connect duration for timer that has not started." ) return current_time() - self._start_connect @property def connect_timeout(self): """Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None """ if self.total is None: return self._connect if self._connect is None or self._connect is self.DEFAULT_TIMEOUT: return self.total return min(self._connect, self.total) @property def read_timeout(self): """Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object. """ if ( self.total is not None and self.total is not self.DEFAULT_TIMEOUT and self._read is not None and self._read is not self.DEFAULT_TIMEOUT ): # In case the connect timeout has not yet been established. if self._start_connect is None: return self._read return max(0, min(self.total - self.get_connect_duration(), self._read)) elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT: return max(0, self.total - self.get_connect_duration()) else: return self._read
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/timeout.py
timeout.py
from __future__ import absolute_import import email import logging import re import time import warnings from collections import namedtuple from itertools import takewhile from ..exceptions import ( ConnectTimeoutError, InvalidHeader, MaxRetryError, ProtocolError, ProxyError, ReadTimeoutError, ResponseError, ) from ..packages import six log = logging.getLogger(__name__) # Data structure for representing the metadata of requests that result in a retry. RequestHistory = namedtuple( "RequestHistory", ["method", "url", "error", "status", "redirect_location"] ) # TODO: In v2 we can remove this sentinel and metaclass with deprecated options. _Default = object() class _RetryMeta(type): @property def DEFAULT_METHOD_WHITELIST(cls): warnings.warn( "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and " "will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead", DeprecationWarning, ) return cls.DEFAULT_ALLOWED_METHODS @DEFAULT_METHOD_WHITELIST.setter def DEFAULT_METHOD_WHITELIST(cls, value): warnings.warn( "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and " "will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead", DeprecationWarning, ) cls.DEFAULT_ALLOWED_METHODS = value @property def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls): warnings.warn( "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and " "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead", DeprecationWarning, ) return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT @DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value): warnings.warn( "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and " "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead", DeprecationWarning, ) cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value @property def BACKOFF_MAX(cls): warnings.warn( "Using 'Retry.BACKOFF_MAX' is deprecated and " "will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead", DeprecationWarning, ) return cls.DEFAULT_BACKOFF_MAX @BACKOFF_MAX.setter def BACKOFF_MAX(cls, value): warnings.warn( "Using 'Retry.BACKOFF_MAX' is deprecated and " "will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead", DeprecationWarning, ) cls.DEFAULT_BACKOFF_MAX = value @six.add_metaclass(_RetryMeta) class Retry(object): """Retry configuration. Each retry attempt will create a new Retry object with updated values, so they can be safely reused. Retries can be defined as a default for a pool:: retries = Retry(connect=5, read=2, redirect=5) http = PoolManager(retries=retries) response = http.request('GET', 'http://example.com/') Or per-request (which overrides the default for the pool):: response = http.request('GET', 'http://example.com/', retries=Retry(10)) Retries can be disabled by passing ``False``:: response = http.request('GET', 'http://example.com/', retries=False) Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless retries are disabled, in which case the causing exception will be raised. :param int total: Total number of retries to allow. Takes precedence over other counts. Set to ``None`` to remove this constraint and fall back on other counts. Set to ``0`` to fail on the first retry. Set to ``False`` to disable and imply ``raise_on_redirect=False``. :param int connect: How many connection-related errors to retry on. These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request. Set to ``0`` to fail on the first retry of this type. :param int read: How many times to retry on read errors. These errors are raised after the request was sent to the server, so the request may have side-effects. Set to ``0`` to fail on the first retry of this type. :param int redirect: How many redirects to perform. Limit this to avoid infinite redirect loops. A redirect is a HTTP response with a status code 301, 302, 303, 307 or 308. Set to ``0`` to fail on the first retry of this type. Set to ``False`` to disable and imply ``raise_on_redirect=False``. :param int status: How many times to retry on bad status codes. These are retries made on responses, where status code matches ``status_forcelist``. Set to ``0`` to fail on the first retry of this type. :param int other: How many times to retry on other errors. Other errors are errors that are not connect, read, redirect or status errors. These errors might be raised after the request was sent to the server, so the request might have side-effects. Set to ``0`` to fail on the first retry of this type. If ``total`` is not set, it's a good idea to set this to 0 to account for unexpected edge cases and avoid infinite retry loops. :param iterable allowed_methods: Set of uppercased HTTP method verbs that we should retry on. By default, we only retry on methods which are considered to be idempotent (multiple requests with the same parameters end with the same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`. Set to a ``False`` value to retry on any verb. .. warning:: Previously this parameter was named ``method_whitelist``, that usage is deprecated in v1.26.0 and will be removed in v2.0. :param iterable status_forcelist: A set of integer HTTP status codes that we should force a retry on. A retry is initiated if the request method is in ``allowed_methods`` and the response status code is in ``status_forcelist``. By default, this is disabled with ``None``. :param float backoff_factor: A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). urllib3 will sleep for:: {backoff factor} * (2 ** ({number of total retries} - 1)) seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer than :attr:`Retry.DEFAULT_BACKOFF_MAX`. By default, backoff is disabled (set to 0). :param bool raise_on_redirect: Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range. :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: whether we should raise an exception, or return a response, if status falls in ``status_forcelist`` range and retries have been exhausted. :param tuple history: The history of the request encountered during each call to :meth:`~Retry.increment`. The list is in the order the requests occurred. Each list item is of class :class:`RequestHistory`. :param bool respect_retry_after_header: Whether to respect Retry-After header on status codes defined as :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. :param iterable remove_headers_on_redirect: Sequence of headers to remove from the request when a response indicating a redirect is returned before firing off the redirected request. """ #: Default methods to be used for ``allowed_methods`` DEFAULT_ALLOWED_METHODS = frozenset( ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] ) #: Default status codes to be used for ``status_forcelist`` RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) #: Default headers to be used for ``remove_headers_on_redirect`` DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(["Authorization"]) #: Maximum backoff time. DEFAULT_BACKOFF_MAX = 120 def __init__( self, total=10, connect=None, read=None, redirect=None, status=None, other=None, allowed_methods=_Default, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True, remove_headers_on_redirect=_Default, # TODO: Deprecated, remove in v2.0 method_whitelist=_Default, ): if method_whitelist is not _Default: if allowed_methods is not _Default: raise ValueError( "Using both 'allowed_methods' and " "'method_whitelist' together is not allowed. " "Instead only use 'allowed_methods'" ) warnings.warn( "Using 'method_whitelist' with Retry is deprecated and " "will be removed in v2.0. Use 'allowed_methods' instead", DeprecationWarning, stacklevel=2, ) allowed_methods = method_whitelist if allowed_methods is _Default: allowed_methods = self.DEFAULT_ALLOWED_METHODS if remove_headers_on_redirect is _Default: remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT self.total = total self.connect = connect self.read = read self.status = status self.other = other if redirect is False or total is False: redirect = 0 raise_on_redirect = False self.redirect = redirect self.status_forcelist = status_forcelist or set() self.allowed_methods = allowed_methods self.backoff_factor = backoff_factor self.raise_on_redirect = raise_on_redirect self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header self.remove_headers_on_redirect = frozenset( [h.lower() for h in remove_headers_on_redirect] ) def new(self, **kw): params = dict( total=self.total, connect=self.connect, read=self.read, redirect=self.redirect, status=self.status, other=self.other, status_forcelist=self.status_forcelist, backoff_factor=self.backoff_factor, raise_on_redirect=self.raise_on_redirect, raise_on_status=self.raise_on_status, history=self.history, remove_headers_on_redirect=self.remove_headers_on_redirect, respect_retry_after_header=self.respect_retry_after_header, ) # TODO: If already given in **kw we use what's given to us # If not given we need to figure out what to pass. We decide # based on whether our class has the 'method_whitelist' property # and if so we pass the deprecated 'method_whitelist' otherwise # we use 'allowed_methods'. Remove in v2.0 if "method_whitelist" not in kw and "allowed_methods" not in kw: if "method_whitelist" in self.__dict__: warnings.warn( "Using 'method_whitelist' with Retry is deprecated and " "will be removed in v2.0. Use 'allowed_methods' instead", DeprecationWarning, ) params["method_whitelist"] = self.allowed_methods else: params["allowed_methods"] = self.allowed_methods params.update(kw) return type(self)(**params) @classmethod def from_int(cls, retries, redirect=True, default=None): """Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r", retries, new_retries) return new_retries def get_backoff_time(self): """Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len( list( takewhile(lambda x: x.redirect_location is None, reversed(self.history)) ) ) if consecutive_errors_len <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) return min(self.DEFAULT_BACKOFF_MAX, backoff_value) def parse_retry_after(self, retry_after): # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 if re.match(r"^\s*[0-9]+\s*$", retry_after): seconds = int(retry_after) else: retry_date_tuple = email.utils.parsedate_tz(retry_after) if retry_date_tuple is None: raise InvalidHeader("Invalid Retry-After header: %s" % retry_after) if retry_date_tuple[9] is None: # Python 2 # Assume UTC if no timezone was specified # On Python2.7, parsedate_tz returns None for a timezone offset # instead of 0 if no timezone is given, where mktime_tz treats # a None timezone offset as local time. retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:] retry_date = email.utils.mktime_tz(retry_date_tuple) seconds = retry_date - time.time() if seconds < 0: seconds = 0 return seconds def get_retry_after(self, response): """Get the value of Retry-After in seconds.""" retry_after = response.getheader("Retry-After") if retry_after is None: return None return self.parse_retry_after(retry_after) def sleep_for_retry(self, response=None): retry_after = self.get_retry_after(response) if retry_after: time.sleep(retry_after) return True return False def _sleep_backoff(self): backoff = self.get_backoff_time() if backoff <= 0: return time.sleep(backoff) def sleep(self, response=None): """Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately. """ if self.respect_retry_after_header and response: slept = self.sleep_for_retry(response) if slept: return self._sleep_backoff() def _is_connection_error(self, err): """Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry. """ if isinstance(err, ProxyError): err = err.original_error return isinstance(err, ConnectTimeoutError) def _is_read_error(self, err): """Errors that occur after the request has been started, so we should assume that the server began processing it. """ return isinstance(err, (ReadTimeoutError, ProtocolError)) def _is_method_retryable(self, method): """Checks if a given HTTP method should be retried upon, depending if it is included in the allowed_methods """ # TODO: For now favor if the Retry implementation sets its own method_whitelist # property outside of our constructor to avoid breaking custom implementations. if "method_whitelist" in self.__dict__: warnings.warn( "Using 'method_whitelist' with Retry is deprecated and " "will be removed in v2.0. Use 'allowed_methods' instead", DeprecationWarning, ) allowed_methods = self.method_whitelist else: allowed_methods = self.allowed_methods if allowed_methods and method.upper() not in allowed_methods: return False return True def is_retry(self, method, status_code, has_retry_after=False): """Is this method/status code retryable? (Based on allowlists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header) """ if not self._is_method_retryable(method): return False if self.status_forcelist and status_code in self.status_forcelist: return True return ( self.total and self.respect_retry_after_header and has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES) ) def is_exhausted(self): """Are we out of retries?""" retry_counts = ( self.total, self.connect, self.read, self.redirect, self.status, self.other, ) retry_counts = list(filter(None, retry_counts)) if not retry_counts: return False return min(retry_counts) < 0 def increment( self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None, ): """Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or None if the response was received successfully. :return: A new ``Retry`` object. """ if self.total is False and error: # Disabled, indicate to re-raise the error. raise six.reraise(type(error), error, _stacktrace) total = self.total if total is not None: total -= 1 connect = self.connect read = self.read redirect = self.redirect status_count = self.status other = self.other cause = "unknown" status = None redirect_location = None if error and self._is_connection_error(error): # Connect retry? if connect is False: raise six.reraise(type(error), error, _stacktrace) elif connect is not None: connect -= 1 elif error and self._is_read_error(error): # Read retry? if read is False or not self._is_method_retryable(method): raise six.reraise(type(error), error, _stacktrace) elif read is not None: read -= 1 elif error: # Other retry? if other is not None: other -= 1 elif response and response.get_redirect_location(): # Redirect retry? if redirect is not None: redirect -= 1 cause = "too many redirects" redirect_location = response.get_redirect_location() status = response.status else: # Incrementing because of a server error like a 500 in # status_forcelist and the given method is in the allowed_methods cause = ResponseError.GENERIC_ERROR if response and response.status: if status_count is not None: status_count -= 1 cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status) status = response.status history = self.history + ( RequestHistory(method, url, error, status, redirect_location), ) new_retry = self.new( total=total, connect=connect, read=read, redirect=redirect, status=status_count, other=other, history=history, ) if new_retry.is_exhausted(): raise MaxRetryError(_pool, url, error or ResponseError(cause)) log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) return new_retry def __repr__(self): return ( "{cls.__name__}(total={self.total}, connect={self.connect}, " "read={self.read}, redirect={self.redirect}, status={self.status})" ).format(cls=type(self), self=self) def __getattr__(self, item): if item == "method_whitelist": # TODO: Remove this deprecated alias in v2.0 warnings.warn( "Using 'method_whitelist' with Retry is deprecated and " "will be removed in v2.0. Use 'allowed_methods' instead", DeprecationWarning, ) return self.allowed_methods try: return getattr(super(Retry, self), item) except AttributeError: return getattr(Retry, item) # For backwards compatibility (equivalent to pre-v1.9): Retry.DEFAULT = Retry(3)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/urllib3/util/retry.py
retry.py
import warnings from typing import Dict, Optional, Union from .api import from_bytes, from_fp, from_path, normalize from .constant import CHARDET_CORRESPONDENCE from .models import CharsetMatch, CharsetMatches def detect(byte_str: bytes) -> Dict[str, Optional[Union[str, float]]]: """ chardet legacy method Detect the encoding of the given byte string. It should be mostly backward-compatible. Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it) This function is deprecated and should be used to migrate your project easily, consult the documentation for further information. Not planned for removal. :param byte_str: The byte sequence to examine. """ if not isinstance(byte_str, (bytearray, bytes)): raise TypeError( # pragma: nocover "Expected object of type bytes or bytearray, got: " "{0}".format(type(byte_str)) ) if isinstance(byte_str, bytearray): byte_str = bytes(byte_str) r = from_bytes(byte_str).best() encoding = r.encoding if r is not None else None language = r.language if r is not None and r.language != "Unknown" else "" confidence = 1.0 - r.chaos if r is not None else None # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process # but chardet does return 'utf-8-sig' and it is a valid codec name. if r is not None and encoding == "utf_8" and r.bom: encoding += "_sig" return { "encoding": encoding if encoding not in CHARDET_CORRESPONDENCE else CHARDET_CORRESPONDENCE[encoding], "language": language, "confidence": confidence, } class CharsetNormalizerMatch(CharsetMatch): pass class CharsetNormalizerMatches(CharsetMatches): @staticmethod def from_fp(*args, **kwargs): # type: ignore warnings.warn( # pragma: nocover "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " "and scheduled to be removed in 3.0", DeprecationWarning, ) return from_fp(*args, **kwargs) # pragma: nocover @staticmethod def from_bytes(*args, **kwargs): # type: ignore warnings.warn( # pragma: nocover "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " "and scheduled to be removed in 3.0", DeprecationWarning, ) return from_bytes(*args, **kwargs) # pragma: nocover @staticmethod def from_path(*args, **kwargs): # type: ignore warnings.warn( # pragma: nocover "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " "and scheduled to be removed in 3.0", DeprecationWarning, ) return from_path(*args, **kwargs) # pragma: nocover @staticmethod def normalize(*args, **kwargs): # type: ignore warnings.warn( # pragma: nocover "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " "and scheduled to be removed in 3.0", DeprecationWarning, ) return normalize(*args, **kwargs) # pragma: nocover class CharsetDetector(CharsetNormalizerMatches): pass class CharsetDoctor(CharsetNormalizerMatches): pass
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/legacy.py
legacy.py
import importlib from codecs import IncrementalDecoder from collections import Counter, OrderedDict from functools import lru_cache from typing import Dict, List, Optional, Tuple from .assets import FREQUENCIES from .constant import KO_NAMES, LANGUAGE_SUPPORTED_COUNT, TOO_SMALL_SEQUENCE, ZH_NAMES from .md import is_suspiciously_successive_range from .models import CoherenceMatches from .utils import ( is_accentuated, is_latin, is_multi_byte_encoding, is_unicode_range_secondary, unicode_range, ) def encoding_unicode_range(iana_name: str) -> List[str]: """ Return associated unicode ranges in a single byte code page. """ if is_multi_byte_encoding(iana_name): raise IOError("Function not supported on multi-byte code page") decoder = importlib.import_module("encodings.{}".format(iana_name)).IncrementalDecoder # type: ignore p = decoder(errors="ignore") # type: IncrementalDecoder seen_ranges = {} # type: Dict[str, int] character_count = 0 # type: int for i in range(0x40, 0xFF): chunk = p.decode(bytes([i])) # type: str if chunk: character_range = unicode_range(chunk) # type: Optional[str] if character_range is None: continue if is_unicode_range_secondary(character_range) is False: if character_range not in seen_ranges: seen_ranges[character_range] = 0 seen_ranges[character_range] += 1 character_count += 1 return sorted( [ character_range for character_range in seen_ranges if seen_ranges[character_range] / character_count >= 0.15 ] ) def unicode_range_languages(primary_range: str) -> List[str]: """ Return inferred languages used with a unicode range. """ languages = [] # type: List[str] for language, characters in FREQUENCIES.items(): for character in characters: if unicode_range(character) == primary_range: languages.append(language) break return languages @lru_cache() def encoding_languages(iana_name: str) -> List[str]: """ Single-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ unicode_ranges = encoding_unicode_range(iana_name) # type: List[str] primary_range = None # type: Optional[str] for specified_range in unicode_ranges: if "Latin" not in specified_range: primary_range = specified_range break if primary_range is None: return ["Latin Based"] return unicode_range_languages(primary_range) @lru_cache() def mb_encoding_languages(iana_name: str) -> List[str]: """ Multi-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ if ( iana_name.startswith("shift_") or iana_name.startswith("iso2022_jp") or iana_name.startswith("euc_j") or iana_name == "cp932" ): return ["Japanese"] if iana_name.startswith("gb") or iana_name in ZH_NAMES: return ["Chinese", "Classical Chinese"] if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: return ["Korean"] return [] @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) def get_target_features(language: str) -> Tuple[bool, bool]: """ Determine main aspects from a supported language if it contains accents and if is pure Latin. """ target_have_accents = False # type: bool target_pure_latin = True # type: bool for character in FREQUENCIES[language]: if not target_have_accents and is_accentuated(character): target_have_accents = True if target_pure_latin and is_latin(character) is False: target_pure_latin = False return target_have_accents, target_pure_latin def alphabet_languages( characters: List[str], ignore_non_latin: bool = False ) -> List[str]: """ Return associated languages associated to given characters. """ languages = [] # type: List[Tuple[str, float]] source_have_accents = any(is_accentuated(character) for character in characters) for language, language_characters in FREQUENCIES.items(): target_have_accents, target_pure_latin = get_target_features(language) if ignore_non_latin and target_pure_latin is False: continue if target_have_accents is False and source_have_accents: continue character_count = len(language_characters) # type: int character_match_count = len( [c for c in language_characters if c in characters] ) # type: int ratio = character_match_count / character_count # type: float if ratio >= 0.2: languages.append((language, ratio)) languages = sorted(languages, key=lambda x: x[1], reverse=True) return [compatible_language[0] for compatible_language in languages] def characters_popularity_compare( language: str, ordered_characters: List[str] ) -> float: """ Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) """ if language not in FREQUENCIES: raise ValueError("{} not available".format(language)) character_approved_count = 0 # type: int for character in ordered_characters: if character not in FREQUENCIES[language]: continue characters_before_source = FREQUENCIES[language][ 0 : FREQUENCIES[language].index(character) ] # type: List[str] characters_after_source = FREQUENCIES[language][ FREQUENCIES[language].index(character) : ] # type: List[str] characters_before = ordered_characters[ 0 : ordered_characters.index(character) ] # type: List[str] characters_after = ordered_characters[ ordered_characters.index(character) : ] # type: List[str] before_match_count = [ e in characters_before for e in characters_before_source ].count( True ) # type: int after_match_count = [ e in characters_after for e in characters_after_source ].count( True ) # type: int if len(characters_before_source) == 0 and before_match_count <= 4: character_approved_count += 1 continue if len(characters_after_source) == 0 and after_match_count <= 4: character_approved_count += 1 continue if ( before_match_count / len(characters_before_source) >= 0.4 or after_match_count / len(characters_after_source) >= 0.4 ): character_approved_count += 1 continue return character_approved_count / len(ordered_characters) def alpha_unicode_split(decoded_sequence: str) -> List[str]: """ Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; One containing the latin letters and the other hebrew. """ layers = OrderedDict() # type: Dict[str, str] for character in decoded_sequence: if character.isalpha() is False: continue character_range = unicode_range(character) # type: Optional[str] if character_range is None: continue layer_target_range = None # type: Optional[str] for discovered_range in layers: if ( is_suspiciously_successive_range(discovered_range, character_range) is False ): layer_target_range = discovered_range break if layer_target_range is None: layer_target_range = character_range if layer_target_range not in layers: layers[layer_target_range] = character.lower() continue layers[layer_target_range] += character.lower() return list(layers.values()) def merge_coherence_ratios(results: List[CoherenceMatches]) -> CoherenceMatches: """ This function merge results previously given by the function coherence_ratio. The return type is the same as coherence_ratio. """ per_language_ratios = OrderedDict() # type: Dict[str, List[float]] for result in results: for sub_result in result: language, ratio = sub_result if language not in per_language_ratios: per_language_ratios[language] = [ratio] continue per_language_ratios[language].append(ratio) merge = [ ( language, round( sum(per_language_ratios[language]) / len(per_language_ratios[language]), 4, ), ) for language in per_language_ratios ] return sorted(merge, key=lambda x: x[1], reverse=True) @lru_cache(maxsize=2048) def coherence_ratio( decoded_sequence: str, threshold: float = 0.1, lg_inclusion: Optional[str] = None ) -> CoherenceMatches: """ Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers. A layer = Character extraction by alphabets/ranges. """ results = [] # type: List[Tuple[str, float]] ignore_non_latin = False # type: bool sufficient_match_count = 0 # type: int lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else [] if "Latin Based" in lg_inclusion_list: ignore_non_latin = True lg_inclusion_list.remove("Latin Based") for layer in alpha_unicode_split(decoded_sequence): sequence_frequencies = Counter(layer) # type: Counter most_common = sequence_frequencies.most_common() character_count = sum(o for c, o in most_common) # type: int if character_count <= TOO_SMALL_SEQUENCE: continue popular_character_ordered = [c for c, o in most_common] # type: List[str] for language in lg_inclusion_list or alphabet_languages( popular_character_ordered, ignore_non_latin ): ratio = characters_popularity_compare( language, popular_character_ordered ) # type: float if ratio < threshold: continue elif ratio >= 0.8: sufficient_match_count += 1 results.append((language, round(ratio, 4))) if sufficient_match_count >= 3: break return sorted(results, key=lambda x: x[1], reverse=True)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/cd.py
cd.py
from functools import lru_cache from typing import List, Optional from .constant import COMMON_SAFE_ASCII_CHARACTERS, UNICODE_SECONDARY_RANGE_KEYWORD from .utils import ( is_accentuated, is_ascii, is_case_variable, is_cjk, is_emoticon, is_hangul, is_hiragana, is_katakana, is_latin, is_punctuation, is_separator, is_symbol, is_thai, remove_accent, unicode_range, ) class MessDetectorPlugin: """ Base abstract class used for mess detection plugins. All detectors MUST extend and implement given methods. """ def eligible(self, character: str) -> bool: """ Determine if given character should be fed in. """ raise NotImplementedError # pragma: nocover def feed(self, character: str) -> None: """ The main routine to be executed upon character. Insert the logic in witch the text would be considered chaotic. """ raise NotImplementedError # pragma: nocover def reset(self) -> None: # pragma: no cover """ Permit to reset the plugin to the initial state. """ raise NotImplementedError @property def ratio(self) -> float: """ Compute the chaos ratio based on what your feed() has seen. Must NOT be lower than 0.; No restriction gt 0. """ raise NotImplementedError # pragma: nocover class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): def __init__(self) -> None: self._punctuation_count = 0 # type: int self._symbol_count = 0 # type: int self._character_count = 0 # type: int self._last_printable_char = None # type: Optional[str] self._frenzy_symbol_in_word = False # type: bool def eligible(self, character: str) -> bool: return character.isprintable() def feed(self, character: str) -> None: self._character_count += 1 if ( character != self._last_printable_char and character not in COMMON_SAFE_ASCII_CHARACTERS ): if is_punctuation(character): self._punctuation_count += 1 elif ( character.isdigit() is False and is_symbol(character) and is_emoticon(character) is False ): self._symbol_count += 2 self._last_printable_char = character def reset(self) -> None: # pragma: no cover self._punctuation_count = 0 self._character_count = 0 self._symbol_count = 0 @property def ratio(self) -> float: if self._character_count == 0: return 0.0 ratio_of_punctuation = ( self._punctuation_count + self._symbol_count ) / self._character_count # type: float return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0 class TooManyAccentuatedPlugin(MessDetectorPlugin): def __init__(self) -> None: self._character_count = 0 # type: int self._accentuated_count = 0 # type: int def eligible(self, character: str) -> bool: return character.isalpha() def feed(self, character: str) -> None: self._character_count += 1 if is_accentuated(character): self._accentuated_count += 1 def reset(self) -> None: # pragma: no cover self._character_count = 0 self._accentuated_count = 0 @property def ratio(self) -> float: if self._character_count == 0: return 0.0 ratio_of_accentuation = ( self._accentuated_count / self._character_count ) # type: float return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0 class UnprintablePlugin(MessDetectorPlugin): def __init__(self) -> None: self._unprintable_count = 0 # type: int self._character_count = 0 # type: int def eligible(self, character: str) -> bool: return True def feed(self, character: str) -> None: if ( character.isspace() is False # includes \n \t \r \v and character.isprintable() is False and character != "\x1A" # Why? Its the ASCII substitute character. ): self._unprintable_count += 1 self._character_count += 1 def reset(self) -> None: # pragma: no cover self._unprintable_count = 0 @property def ratio(self) -> float: if self._character_count == 0: return 0.0 return (self._unprintable_count * 8) / self._character_count class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): def __init__(self) -> None: self._successive_count = 0 # type: int self._character_count = 0 # type: int self._last_latin_character = None # type: Optional[str] def eligible(self, character: str) -> bool: return character.isalpha() and is_latin(character) def feed(self, character: str) -> None: self._character_count += 1 if ( self._last_latin_character is not None and is_accentuated(character) and is_accentuated(self._last_latin_character) ): if character.isupper() and self._last_latin_character.isupper(): self._successive_count += 1 # Worse if its the same char duplicated with different accent. if remove_accent(character) == remove_accent(self._last_latin_character): self._successive_count += 1 self._last_latin_character = character def reset(self) -> None: # pragma: no cover self._successive_count = 0 self._character_count = 0 self._last_latin_character = None @property def ratio(self) -> float: if self._character_count == 0: return 0.0 return (self._successive_count * 2) / self._character_count class SuspiciousRange(MessDetectorPlugin): def __init__(self) -> None: self._suspicious_successive_range_count = 0 # type: int self._character_count = 0 # type: int self._last_printable_seen = None # type: Optional[str] def eligible(self, character: str) -> bool: return character.isprintable() def feed(self, character: str) -> None: self._character_count += 1 if ( character.isspace() or is_punctuation(character) or character in COMMON_SAFE_ASCII_CHARACTERS ): self._last_printable_seen = None return if self._last_printable_seen is None: self._last_printable_seen = character return unicode_range_a = unicode_range( self._last_printable_seen ) # type: Optional[str] unicode_range_b = unicode_range(character) # type: Optional[str] if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): self._suspicious_successive_range_count += 1 self._last_printable_seen = character def reset(self) -> None: # pragma: no cover self._character_count = 0 self._suspicious_successive_range_count = 0 self._last_printable_seen = None @property def ratio(self) -> float: if self._character_count == 0: return 0.0 ratio_of_suspicious_range_usage = ( self._suspicious_successive_range_count * 2 ) / self._character_count # type: float if ratio_of_suspicious_range_usage < 0.1: return 0.0 return ratio_of_suspicious_range_usage class SuperWeirdWordPlugin(MessDetectorPlugin): def __init__(self) -> None: self._word_count = 0 # type: int self._bad_word_count = 0 # type: int self._foreign_long_count = 0 # type: int self._is_current_word_bad = False # type: bool self._foreign_long_watch = False # type: bool self._character_count = 0 # type: int self._bad_character_count = 0 # type: int self._buffer = "" # type: str self._buffer_accent_count = 0 # type: int def eligible(self, character: str) -> bool: return True def feed(self, character: str) -> None: if character.isalpha(): self._buffer = "".join([self._buffer, character]) if is_accentuated(character): self._buffer_accent_count += 1 if ( self._foreign_long_watch is False and (is_latin(character) is False or is_accentuated(character)) and is_cjk(character) is False and is_hangul(character) is False and is_katakana(character) is False and is_hiragana(character) is False and is_thai(character) is False ): self._foreign_long_watch = True return if not self._buffer: return if ( character.isspace() or is_punctuation(character) or is_separator(character) ) and self._buffer: self._word_count += 1 buffer_length = len(self._buffer) # type: int self._character_count += buffer_length if buffer_length >= 4: if self._buffer_accent_count / buffer_length > 0.34: self._is_current_word_bad = True # Word/Buffer ending with a upper case accentuated letter are so rare, # that we will consider them all as suspicious. Same weight as foreign_long suspicious. if is_accentuated(self._buffer[-1]) and self._buffer[-1].isupper(): self._foreign_long_count += 1 self._is_current_word_bad = True if buffer_length >= 24 and self._foreign_long_watch: self._foreign_long_count += 1 self._is_current_word_bad = True if self._is_current_word_bad: self._bad_word_count += 1 self._bad_character_count += len(self._buffer) self._is_current_word_bad = False self._foreign_long_watch = False self._buffer = "" self._buffer_accent_count = 0 elif ( character not in {"<", ">", "-", "=", "~", "|", "_"} and character.isdigit() is False and is_symbol(character) ): self._is_current_word_bad = True self._buffer += character def reset(self) -> None: # pragma: no cover self._buffer = "" self._is_current_word_bad = False self._foreign_long_watch = False self._bad_word_count = 0 self._word_count = 0 self._character_count = 0 self._bad_character_count = 0 self._foreign_long_count = 0 @property def ratio(self) -> float: if self._word_count <= 10 and self._foreign_long_count == 0: return 0.0 return self._bad_character_count / self._character_count class CjkInvalidStopPlugin(MessDetectorPlugin): """ GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and can be easily detected. Searching for the overuse of '丅' and '丄'. """ def __init__(self) -> None: self._wrong_stop_count = 0 # type: int self._cjk_character_count = 0 # type: int def eligible(self, character: str) -> bool: return True def feed(self, character: str) -> None: if character in {"丅", "丄"}: self._wrong_stop_count += 1 return if is_cjk(character): self._cjk_character_count += 1 def reset(self) -> None: # pragma: no cover self._wrong_stop_count = 0 self._cjk_character_count = 0 @property def ratio(self) -> float: if self._cjk_character_count < 16: return 0.0 return self._wrong_stop_count / self._cjk_character_count class ArchaicUpperLowerPlugin(MessDetectorPlugin): def __init__(self) -> None: self._buf = False # type: bool self._character_count_since_last_sep = 0 # type: int self._successive_upper_lower_count = 0 # type: int self._successive_upper_lower_count_final = 0 # type: int self._character_count = 0 # type: int self._last_alpha_seen = None # type: Optional[str] self._current_ascii_only = True # type: bool def eligible(self, character: str) -> bool: return True def feed(self, character: str) -> None: is_concerned = character.isalpha() and is_case_variable(character) chunk_sep = is_concerned is False if chunk_sep and self._character_count_since_last_sep > 0: if ( self._character_count_since_last_sep <= 64 and character.isdigit() is False and self._current_ascii_only is False ): self._successive_upper_lower_count_final += ( self._successive_upper_lower_count ) self._successive_upper_lower_count = 0 self._character_count_since_last_sep = 0 self._last_alpha_seen = None self._buf = False self._character_count += 1 self._current_ascii_only = True return if self._current_ascii_only is True and is_ascii(character) is False: self._current_ascii_only = False if self._last_alpha_seen is not None: if (character.isupper() and self._last_alpha_seen.islower()) or ( character.islower() and self._last_alpha_seen.isupper() ): if self._buf is True: self._successive_upper_lower_count += 2 self._buf = False else: self._buf = True else: self._buf = False self._character_count += 1 self._character_count_since_last_sep += 1 self._last_alpha_seen = character def reset(self) -> None: # pragma: no cover self._character_count = 0 self._character_count_since_last_sep = 0 self._successive_upper_lower_count = 0 self._successive_upper_lower_count_final = 0 self._last_alpha_seen = None self._buf = False self._current_ascii_only = True @property def ratio(self) -> float: if self._character_count == 0: return 0.0 return self._successive_upper_lower_count_final / self._character_count def is_suspiciously_successive_range( unicode_range_a: Optional[str], unicode_range_b: Optional[str] ) -> bool: """ Determine if two Unicode range seen next to each other can be considered as suspicious. """ if unicode_range_a is None or unicode_range_b is None: return True if unicode_range_a == unicode_range_b: return False if "Latin" in unicode_range_a and "Latin" in unicode_range_b: return False if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b: return False # Latin characters can be accompanied with a combining diacritical mark # eg. Vietnamese. if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and ( "Combining" in unicode_range_a or "Combining" in unicode_range_b ): return False keywords_range_a, keywords_range_b = unicode_range_a.split( " " ), unicode_range_b.split(" ") for el in keywords_range_a: if el in UNICODE_SECONDARY_RANGE_KEYWORD: continue if el in keywords_range_b: return False # Japanese Exception range_a_jp_chars, range_b_jp_chars = ( unicode_range_a in ( "Hiragana", "Katakana", ), unicode_range_b in ("Hiragana", "Katakana"), ) if (range_a_jp_chars or range_b_jp_chars) and ( "CJK" in unicode_range_a or "CJK" in unicode_range_b ): return False if range_a_jp_chars and range_b_jp_chars: return False if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b: if "CJK" in unicode_range_a or "CJK" in unicode_range_b: return False if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": return False # Chinese/Japanese use dedicated range for punctuation and/or separators. if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or ( unicode_range_a in ["Katakana", "Hiragana"] and unicode_range_b in ["Katakana", "Hiragana"] ): if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b: return False if "Forms" in unicode_range_a or "Forms" in unicode_range_b: return False return True @lru_cache(maxsize=2048) def mess_ratio( decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False ) -> float: """ Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. """ detectors = [ md_class() for md_class in MessDetectorPlugin.__subclasses__() ] # type: List[MessDetectorPlugin] length = len(decoded_sequence) + 1 # type: int mean_mess_ratio = 0.0 # type: float if length < 512: intermediary_mean_mess_ratio_calc = 32 # type: int elif length <= 1024: intermediary_mean_mess_ratio_calc = 64 else: intermediary_mean_mess_ratio_calc = 128 for character, index in zip(decoded_sequence + "\n", range(length)): for detector in detectors: if detector.eligible(character): detector.feed(character) if ( index > 0 and index % intermediary_mean_mess_ratio_calc == 0 ) or index == length - 1: mean_mess_ratio = sum(dt.ratio for dt in detectors) if mean_mess_ratio >= maximum_threshold: break if debug: for dt in detectors: # pragma: nocover print(dt.__class__, dt.ratio) return round(mean_mess_ratio, 3)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/md.py
md.py
try: import unicodedata2 as unicodedata except ImportError: import unicodedata # type: ignore[no-redef] import importlib import logging from codecs import IncrementalDecoder from encodings.aliases import aliases from functools import lru_cache from re import findall from typing import List, Optional, Set, Tuple, Union from _multibytecodec import MultibyteIncrementalDecoder # type: ignore from .constant import ( ENCODING_MARKS, IANA_SUPPORTED_SIMILAR, RE_POSSIBLE_ENCODING_INDICATION, UNICODE_RANGES_COMBINED, UNICODE_SECONDARY_RANGE_KEYWORD, UTF8_MAXIMAL_ALLOCATION, ) @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_accentuated(character: str) -> bool: try: description = unicodedata.name(character) # type: str except ValueError: return False return ( "WITH GRAVE" in description or "WITH ACUTE" in description or "WITH CEDILLA" in description or "WITH DIAERESIS" in description or "WITH CIRCUMFLEX" in description or "WITH TILDE" in description ) @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def remove_accent(character: str) -> str: decomposed = unicodedata.decomposition(character) # type: str if not decomposed: return character codes = decomposed.split(" ") # type: List[str] return chr(int(codes[0], 16)) @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def unicode_range(character: str) -> Optional[str]: """ Retrieve the Unicode range official name from a single character. """ character_ord = ord(character) # type: int for range_name, ord_range in UNICODE_RANGES_COMBINED.items(): if character_ord in ord_range: return range_name return None @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_latin(character: str) -> bool: try: description = unicodedata.name(character) # type: str except ValueError: return False return "LATIN" in description def is_ascii(character: str) -> bool: try: character.encode("ascii") except UnicodeEncodeError: return False return True @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_punctuation(character: str) -> bool: character_category = unicodedata.category(character) # type: str if "P" in character_category: return True character_range = unicode_range(character) # type: Optional[str] if character_range is None: return False return "Punctuation" in character_range @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_symbol(character: str) -> bool: character_category = unicodedata.category(character) # type: str if "S" in character_category or "N" in character_category: return True character_range = unicode_range(character) # type: Optional[str] if character_range is None: return False return "Forms" in character_range @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_emoticon(character: str) -> bool: character_range = unicode_range(character) # type: Optional[str] if character_range is None: return False return "Emoticons" in character_range @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_separator(character: str) -> bool: if character.isspace() or character in {"|", "+", ",", ";", "<", ">"}: return True character_category = unicodedata.category(character) # type: str return "Z" in character_category @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_case_variable(character: str) -> bool: return character.islower() != character.isupper() def is_private_use_only(character: str) -> bool: character_category = unicodedata.category(character) # type: str return character_category == "Co" @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_cjk(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False return "CJK" in character_name @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_hiragana(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False return "HIRAGANA" in character_name @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_katakana(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False return "KATAKANA" in character_name @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_hangul(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False return "HANGUL" in character_name @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) def is_thai(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False return "THAI" in character_name @lru_cache(maxsize=len(UNICODE_RANGES_COMBINED)) def is_unicode_range_secondary(range_name: str) -> bool: return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD) def any_specified_encoding(sequence: bytes, search_zone: int = 4096) -> Optional[str]: """ Extract using ASCII-only decoder any specified encoding in the first n-bytes. """ if not isinstance(sequence, bytes): raise TypeError seq_len = len(sequence) # type: int results = findall( RE_POSSIBLE_ENCODING_INDICATION, sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"), ) # type: List[str] if len(results) == 0: return None for specified_encoding in results: specified_encoding = specified_encoding.lower().replace("-", "_") for encoding_alias, encoding_iana in aliases.items(): if encoding_alias == specified_encoding: return encoding_iana if encoding_iana == specified_encoding: return encoding_iana return None @lru_cache(maxsize=128) def is_multi_byte_encoding(name: str) -> bool: """ Verify is a specific encoding is a multi byte one based on it IANA name """ return name in { "utf_8", "utf_8_sig", "utf_16", "utf_16_be", "utf_16_le", "utf_32", "utf_32_le", "utf_32_be", "utf_7", } or issubclass( importlib.import_module("encodings.{}".format(name)).IncrementalDecoder, # type: ignore MultibyteIncrementalDecoder, ) def identify_sig_or_bom(sequence: bytes) -> Tuple[Optional[str], bytes]: """ Identify and extract SIG/BOM in given sequence. """ for iana_encoding in ENCODING_MARKS: marks = ENCODING_MARKS[iana_encoding] # type: Union[bytes, List[bytes]] if isinstance(marks, bytes): marks = [marks] for mark in marks: if sequence.startswith(mark): return iana_encoding, mark return None, b"" def should_strip_sig_or_bom(iana_encoding: str) -> bool: return iana_encoding not in {"utf_16", "utf_32"} def iana_name(cp_name: str, strict: bool = True) -> str: cp_name = cp_name.lower().replace("-", "_") for encoding_alias, encoding_iana in aliases.items(): if cp_name in [encoding_alias, encoding_iana]: return encoding_iana if strict: raise ValueError("Unable to retrieve IANA for '{}'".format(cp_name)) return cp_name def range_scan(decoded_sequence: str) -> List[str]: ranges = set() # type: Set[str] for character in decoded_sequence: character_range = unicode_range(character) # type: Optional[str] if character_range is None: continue ranges.add(character_range) return list(ranges) def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): return 0.0 decoder_a = importlib.import_module("encodings.{}".format(iana_name_a)).IncrementalDecoder # type: ignore decoder_b = importlib.import_module("encodings.{}".format(iana_name_b)).IncrementalDecoder # type: ignore id_a = decoder_a(errors="ignore") # type: IncrementalDecoder id_b = decoder_b(errors="ignore") # type: IncrementalDecoder character_match_count = 0 # type: int for i in range(255): to_be_decoded = bytes([i]) # type: bytes if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): character_match_count += 1 return character_match_count / 254 def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: """ Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using the function cp_similarity. """ return ( iana_name_a in IANA_SUPPORTED_SIMILAR and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] ) def set_logging_handler( name: str = "charset_normalizer", level: int = logging.INFO, format_string: str = "%(asctime)s | %(levelname)s | %(message)s", ) -> None: logger = logging.getLogger(name) logger.setLevel(level) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(format_string)) logger.addHandler(handler)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/utils.py
utils.py
import logging from os.path import basename, splitext from typing import BinaryIO, List, Optional, Set try: from os import PathLike except ImportError: # pragma: no cover PathLike = str # type: ignore from .cd import ( coherence_ratio, encoding_languages, mb_encoding_languages, merge_coherence_ratios, ) from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE from .md import mess_ratio from .models import CharsetMatch, CharsetMatches from .utils import ( any_specified_encoding, iana_name, identify_sig_or_bom, is_cp_similar, is_multi_byte_encoding, should_strip_sig_or_bom, ) # Will most likely be controversial # logging.addLevelName(TRACE, "TRACE") logger = logging.getLogger("charset_normalizer") explain_handler = logging.StreamHandler() explain_handler.setFormatter( logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") ) def from_bytes( sequences: bytes, steps: int = 5, chunk_size: int = 512, threshold: float = 0.2, cp_isolation: List[str] = None, cp_exclusion: List[str] = None, preemptive_behaviour: bool = True, explain: bool = False, ) -> CharsetMatches: """ Given a raw bytes sequence, return the best possibles charset usable to render str objects. If there is no results, it is a strong indicator that the source is binary/not text. By default, the process will extract 5 blocs of 512o each to assess the mess and coherence of a given sequence. And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will. The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page but never take it for granted. Can improve the performance. You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that purpose. This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. Custom logging format and handler can be set manually. """ if not isinstance(sequences, (bytearray, bytes)): raise TypeError( "Expected object of type bytes or bytearray, got: {0}".format( type(sequences) ) ) if explain: previous_logger_level = logger.level # type: int logger.addHandler(explain_handler) logger.setLevel(TRACE) length = len(sequences) # type: int if length == 0: logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level or logging.WARNING) return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")]) if cp_isolation is not None: logger.log( TRACE, "cp_isolation is set. use this flag for debugging purpose. " "limited list of encoding allowed : %s.", ", ".join(cp_isolation), ) cp_isolation = [iana_name(cp, False) for cp in cp_isolation] else: cp_isolation = [] if cp_exclusion is not None: logger.log( TRACE, "cp_exclusion is set. use this flag for debugging purpose. " "limited list of encoding excluded : %s.", ", ".join(cp_exclusion), ) cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] else: cp_exclusion = [] if length <= (chunk_size * steps): logger.log( TRACE, "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", steps, chunk_size, length, ) steps = 1 chunk_size = length if steps > 1 and length / steps < chunk_size: chunk_size = int(length / steps) is_too_small_sequence = len(sequences) < TOO_SMALL_SEQUENCE # type: bool is_too_large_sequence = len(sequences) >= TOO_BIG_SEQUENCE # type: bool if is_too_small_sequence: logger.log( TRACE, "Trying to detect encoding from a tiny portion of ({}) byte(s).".format( length ), ) elif is_too_large_sequence: logger.log( TRACE, "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format( length ), ) prioritized_encodings = [] # type: List[str] specified_encoding = ( any_specified_encoding(sequences) if preemptive_behaviour else None ) # type: Optional[str] if specified_encoding is not None: prioritized_encodings.append(specified_encoding) logger.log( TRACE, "Detected declarative mark in sequence. Priority +1 given for %s.", specified_encoding, ) tested = set() # type: Set[str] tested_but_hard_failure = [] # type: List[str] tested_but_soft_failure = [] # type: List[str] fallback_ascii = None # type: Optional[CharsetMatch] fallback_u8 = None # type: Optional[CharsetMatch] fallback_specified = None # type: Optional[CharsetMatch] results = CharsetMatches() # type: CharsetMatches sig_encoding, sig_payload = identify_sig_or_bom(sequences) if sig_encoding is not None: prioritized_encodings.append(sig_encoding) logger.log( TRACE, "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", len(sig_payload), sig_encoding, ) prioritized_encodings.append("ascii") if "utf_8" not in prioritized_encodings: prioritized_encodings.append("utf_8") for encoding_iana in prioritized_encodings + IANA_SUPPORTED: if cp_isolation and encoding_iana not in cp_isolation: continue if cp_exclusion and encoding_iana in cp_exclusion: continue if encoding_iana in tested: continue tested.add(encoding_iana) decoded_payload = None # type: Optional[str] bom_or_sig_available = sig_encoding == encoding_iana # type: bool strip_sig_or_bom = bom_or_sig_available and should_strip_sig_or_bom( encoding_iana ) # type: bool if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: logger.log( TRACE, "Encoding %s wont be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", encoding_iana, ) continue try: is_multi_byte_decoder = is_multi_byte_encoding(encoding_iana) # type: bool except (ModuleNotFoundError, ImportError): logger.log( TRACE, "Encoding %s does not provide an IncrementalDecoder", encoding_iana, ) continue try: if is_too_large_sequence and is_multi_byte_decoder is False: str( sequences[: int(50e4)] if strip_sig_or_bom is False else sequences[len(sig_payload) : int(50e4)], encoding=encoding_iana, ) else: decoded_payload = str( sequences if strip_sig_or_bom is False else sequences[len(sig_payload) :], encoding=encoding_iana, ) except (UnicodeDecodeError, LookupError) as e: if not isinstance(e, LookupError): logger.log( TRACE, "Code page %s does not fit given bytes sequence at ALL. %s", encoding_iana, str(e), ) tested_but_hard_failure.append(encoding_iana) continue similar_soft_failure_test = False # type: bool for encoding_soft_failed in tested_but_soft_failure: if is_cp_similar(encoding_iana, encoding_soft_failed): similar_soft_failure_test = True break if similar_soft_failure_test: logger.log( TRACE, "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!", encoding_iana, encoding_soft_failed, ) continue r_ = range( 0 if not bom_or_sig_available else len(sig_payload), length, int(length / steps), ) multi_byte_bonus = ( is_multi_byte_decoder and decoded_payload is not None and len(decoded_payload) < length ) # type: bool if multi_byte_bonus: logger.log( TRACE, "Code page %s is a multi byte encoding table and it appear that at least one character " "was encoded using n-bytes.", encoding_iana, ) max_chunk_gave_up = int(len(r_) / 4) # type: int max_chunk_gave_up = max(max_chunk_gave_up, 2) early_stop_count = 0 # type: int lazy_str_hard_failure = False md_chunks = [] # type: List[str] md_ratios = [] for i in r_: if i + chunk_size > length + 8: continue cut_sequence = sequences[i : i + chunk_size] if bom_or_sig_available and strip_sig_or_bom is False: cut_sequence = sig_payload + cut_sequence try: chunk = cut_sequence.decode( encoding_iana, errors="ignore" if is_multi_byte_decoder else "strict", ) # type: str except UnicodeDecodeError as e: # Lazy str loading may have missed something there logger.log( TRACE, "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", encoding_iana, str(e), ) early_stop_count = max_chunk_gave_up lazy_str_hard_failure = True break # multi-byte bad cutting detector and adjustment # not the cleanest way to perform that fix but clever enough for now. if is_multi_byte_decoder and i > 0 and sequences[i] >= 0x80: chunk_partial_size_chk = min(chunk_size, 16) # type: int if ( decoded_payload and chunk[:chunk_partial_size_chk] not in decoded_payload ): for j in range(i, i - 4, -1): cut_sequence = sequences[j : i + chunk_size] if bom_or_sig_available and strip_sig_or_bom is False: cut_sequence = sig_payload + cut_sequence chunk = cut_sequence.decode(encoding_iana, errors="ignore") if chunk[:chunk_partial_size_chk] in decoded_payload: break md_chunks.append(chunk) md_ratios.append(mess_ratio(chunk, threshold)) if md_ratios[-1] >= threshold: early_stop_count += 1 if (early_stop_count >= max_chunk_gave_up) or ( bom_or_sig_available and strip_sig_or_bom is False ): break # We might want to check the sequence again with the whole content # Only if initial MD tests passes if ( not lazy_str_hard_failure and is_too_large_sequence and not is_multi_byte_decoder ): try: sequences[int(50e3) :].decode(encoding_iana, errors="strict") except UnicodeDecodeError as e: logger.log( TRACE, "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", encoding_iana, str(e), ) tested_but_hard_failure.append(encoding_iana) continue mean_mess_ratio = ( sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 ) # type: float if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: tested_but_soft_failure.append(encoding_iana) logger.log( TRACE, "%s was excluded because of initial chaos probing. Gave up %i time(s). " "Computed mean chaos is %f %%.", encoding_iana, early_stop_count, round(mean_mess_ratio * 100, ndigits=3), ) # Preparing those fallbacks in case we got nothing. if ( encoding_iana in ["ascii", "utf_8", specified_encoding] and not lazy_str_hard_failure ): fallback_entry = CharsetMatch( sequences, encoding_iana, threshold, False, [], decoded_payload ) if encoding_iana == specified_encoding: fallback_specified = fallback_entry elif encoding_iana == "ascii": fallback_ascii = fallback_entry else: fallback_u8 = fallback_entry continue logger.log( TRACE, "%s passed initial chaos probing. Mean measured chaos is %f %%", encoding_iana, round(mean_mess_ratio * 100, ndigits=3), ) if not is_multi_byte_decoder: target_languages = encoding_languages(encoding_iana) # type: List[str] else: target_languages = mb_encoding_languages(encoding_iana) if target_languages: logger.log( TRACE, "{} should target any language(s) of {}".format( encoding_iana, str(target_languages) ), ) cd_ratios = [] # We shall skip the CD when its about ASCII # Most of the time its not relevant to run "language-detection" on it. if encoding_iana != "ascii": for chunk in md_chunks: chunk_languages = coherence_ratio( chunk, 0.1, ",".join(target_languages) if target_languages else None ) cd_ratios.append(chunk_languages) cd_ratios_merged = merge_coherence_ratios(cd_ratios) if cd_ratios_merged: logger.log( TRACE, "We detected language {} using {}".format( cd_ratios_merged, encoding_iana ), ) results.append( CharsetMatch( sequences, encoding_iana, mean_mess_ratio, bom_or_sig_available, cd_ratios_merged, decoded_payload, ) ) if ( encoding_iana in [specified_encoding, "ascii", "utf_8"] and mean_mess_ratio < 0.1 ): logger.debug( "Encoding detection: %s is most likely the one.", encoding_iana ) if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level) return CharsetMatches([results[encoding_iana]]) if encoding_iana == sig_encoding: logger.debug( "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " "the beginning of the sequence.", encoding_iana, ) if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level) return CharsetMatches([results[encoding_iana]]) if len(results) == 0: if fallback_u8 or fallback_ascii or fallback_specified: logger.log( TRACE, "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", ) if fallback_specified: logger.debug( "Encoding detection: %s will be used as a fallback match", fallback_specified.encoding, ) results.append(fallback_specified) elif ( (fallback_u8 and fallback_ascii is None) or ( fallback_u8 and fallback_ascii and fallback_u8.fingerprint != fallback_ascii.fingerprint ) or (fallback_u8 is not None) ): logger.debug("Encoding detection: utf_8 will be used as a fallback match") results.append(fallback_u8) elif fallback_ascii: logger.debug("Encoding detection: ascii will be used as a fallback match") results.append(fallback_ascii) if results: logger.debug( "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", results.best().encoding, # type: ignore len(results) - 1, ) else: logger.debug("Encoding detection: Unable to determine any suitable charset.") if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level) return results def from_fp( fp: BinaryIO, steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: List[str] = None, cp_exclusion: List[str] = None, preemptive_behaviour: bool = True, explain: bool = False, ) -> CharsetMatches: """ Same thing than the function from_bytes but using a file pointer that is already ready. Will not close the file pointer. """ return from_bytes( fp.read(), steps, chunk_size, threshold, cp_isolation, cp_exclusion, preemptive_behaviour, explain, ) def from_path( path: PathLike, steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: List[str] = None, cp_exclusion: List[str] = None, preemptive_behaviour: bool = True, explain: bool = False, ) -> CharsetMatches: """ Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. Can raise IOError. """ with open(path, "rb") as fp: return from_fp( fp, steps, chunk_size, threshold, cp_isolation, cp_exclusion, preemptive_behaviour, explain, ) def normalize( path: PathLike, steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: List[str] = None, cp_exclusion: List[str] = None, preemptive_behaviour: bool = True, ) -> CharsetMatch: """ Take a (text-based) file path and try to create another file next to it, this time using UTF-8. """ results = from_path( path, steps, chunk_size, threshold, cp_isolation, cp_exclusion, preemptive_behaviour, ) filename = basename(path) target_extensions = list(splitext(filename)) if len(results) == 0: raise IOError( 'Unable to normalize "{}", no encoding charset seems to fit.'.format( filename ) ) result = results.best() target_extensions[0] += "-" + result.encoding # type: ignore with open( "{}".format(str(path).replace(filename, "".join(target_extensions))), "wb" ) as fp: fp.write(result.output()) # type: ignore return result # type: ignore
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/api.py
api.py
import warnings from collections import Counter from encodings.aliases import aliases from hashlib import sha256 from json import dumps from re import sub from typing import Any, Dict, Iterator, List, Optional, Tuple, Union from .constant import NOT_PRINTABLE_PATTERN, TOO_BIG_SEQUENCE from .md import mess_ratio from .utils import iana_name, is_multi_byte_encoding, unicode_range class CharsetMatch: def __init__( self, payload: bytes, guessed_encoding: str, mean_mess_ratio: float, has_sig_or_bom: bool, languages: "CoherenceMatches", decoded_payload: Optional[str] = None, ): self._payload = payload # type: bytes self._encoding = guessed_encoding # type: str self._mean_mess_ratio = mean_mess_ratio # type: float self._languages = languages # type: CoherenceMatches self._has_sig_or_bom = has_sig_or_bom # type: bool self._unicode_ranges = None # type: Optional[List[str]] self._leaves = [] # type: List[CharsetMatch] self._mean_coherence_ratio = 0.0 # type: float self._output_payload = None # type: Optional[bytes] self._output_encoding = None # type: Optional[str] self._string = decoded_payload # type: Optional[str] def __eq__(self, other: object) -> bool: if not isinstance(other, CharsetMatch): raise TypeError( "__eq__ cannot be invoked on {} and {}.".format( str(other.__class__), str(self.__class__) ) ) return self.encoding == other.encoding and self.fingerprint == other.fingerprint def __lt__(self, other: object) -> bool: """ Implemented to make sorted available upon CharsetMatches items. """ if not isinstance(other, CharsetMatch): raise ValueError chaos_difference = abs(self.chaos - other.chaos) # type: float coherence_difference = abs(self.coherence - other.coherence) # type: float # Bellow 1% difference --> Use Coherence if chaos_difference < 0.01 and coherence_difference > 0.02: # When having a tough decision, use the result that decoded as many multi-byte as possible. if chaos_difference == 0.0 and self.coherence == other.coherence: return self.multi_byte_usage > other.multi_byte_usage return self.coherence > other.coherence return self.chaos < other.chaos @property def multi_byte_usage(self) -> float: return 1.0 - len(str(self)) / len(self.raw) @property def chaos_secondary_pass(self) -> float: """ Check once again chaos in decoded text, except this time, with full content. Use with caution, this can be very slow. Notice: Will be removed in 3.0 """ warnings.warn( "chaos_secondary_pass is deprecated and will be removed in 3.0", DeprecationWarning, ) return mess_ratio(str(self), 1.0) @property def coherence_non_latin(self) -> float: """ Coherence ratio on the first non-latin language detected if ANY. Notice: Will be removed in 3.0 """ warnings.warn( "coherence_non_latin is deprecated and will be removed in 3.0", DeprecationWarning, ) return 0.0 @property def w_counter(self) -> Counter: """ Word counter instance on decoded text. Notice: Will be removed in 3.0 """ warnings.warn( "w_counter is deprecated and will be removed in 3.0", DeprecationWarning ) string_printable_only = sub(NOT_PRINTABLE_PATTERN, " ", str(self).lower()) return Counter(string_printable_only.split()) def __str__(self) -> str: # Lazy Str Loading if self._string is None: self._string = str(self._payload, self._encoding, "strict") return self._string def __repr__(self) -> str: return "<CharsetMatch '{}' bytes({})>".format(self.encoding, self.fingerprint) def add_submatch(self, other: "CharsetMatch") -> None: if not isinstance(other, CharsetMatch) or other == self: raise ValueError( "Unable to add instance <{}> as a submatch of a CharsetMatch".format( other.__class__ ) ) other._string = None # Unload RAM usage; dirty trick. self._leaves.append(other) @property def encoding(self) -> str: return self._encoding @property def encoding_aliases(self) -> List[str]: """ Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855. """ also_known_as = [] # type: List[str] for u, p in aliases.items(): if self.encoding == u: also_known_as.append(p) elif self.encoding == p: also_known_as.append(u) return also_known_as @property def bom(self) -> bool: return self._has_sig_or_bom @property def byte_order_mark(self) -> bool: return self._has_sig_or_bom @property def languages(self) -> List[str]: """ Return the complete list of possible languages found in decoded sequence. Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. """ return [e[0] for e in self._languages] @property def language(self) -> str: """ Most probable language found in decoded sequence. If none were detected or inferred, the property will return "Unknown". """ if not self._languages: # Trying to infer the language based on the given encoding # Its either English or we should not pronounce ourselves in certain cases. if "ascii" in self.could_be_from_charset: return "English" # doing it there to avoid circular import from charset_normalizer.cd import encoding_languages, mb_encoding_languages languages = ( mb_encoding_languages(self.encoding) if is_multi_byte_encoding(self.encoding) else encoding_languages(self.encoding) ) if len(languages) == 0 or "Latin Based" in languages: return "Unknown" return languages[0] return self._languages[0][0] @property def chaos(self) -> float: return self._mean_mess_ratio @property def coherence(self) -> float: if not self._languages: return 0.0 return self._languages[0][1] @property def percent_chaos(self) -> float: return round(self.chaos * 100, ndigits=3) @property def percent_coherence(self) -> float: return round(self.coherence * 100, ndigits=3) @property def raw(self) -> bytes: """ Original untouched bytes. """ return self._payload @property def submatch(self) -> List["CharsetMatch"]: return self._leaves @property def has_submatch(self) -> bool: return len(self._leaves) > 0 @property def alphabets(self) -> List[str]: if self._unicode_ranges is not None: return self._unicode_ranges # list detected ranges detected_ranges = [ unicode_range(char) for char in str(self) ] # type: List[Optional[str]] # filter and sort self._unicode_ranges = sorted(list({r for r in detected_ranges if r})) return self._unicode_ranges @property def could_be_from_charset(self) -> List[str]: """ The complete list of encoding that output the exact SAME str result and therefore could be the originating encoding. This list does include the encoding available in property 'encoding'. """ return [self._encoding] + [m.encoding for m in self._leaves] def first(self) -> "CharsetMatch": """ Kept for BC reasons. Will be removed in 3.0. """ return self def best(self) -> "CharsetMatch": """ Kept for BC reasons. Will be removed in 3.0. """ return self def output(self, encoding: str = "utf_8") -> bytes: """ Method to get re-encoded bytes payload using given target encoding. Default to UTF-8. Any errors will be simply ignored by the encoder NOT replaced. """ if self._output_encoding is None or self._output_encoding != encoding: self._output_encoding = encoding self._output_payload = str(self).encode(encoding, "replace") return self._output_payload # type: ignore @property def fingerprint(self) -> str: """ Retrieve the unique SHA256 computed using the transformed (re-encoded) payload. Not the original one. """ return sha256(self.output()).hexdigest() class CharsetMatches: """ Container with every CharsetMatch items ordered by default from most probable to the less one. Act like a list(iterable) but does not implements all related methods. """ def __init__(self, results: List[CharsetMatch] = None): self._results = sorted(results) if results else [] # type: List[CharsetMatch] def __iter__(self) -> Iterator[CharsetMatch]: yield from self._results def __getitem__(self, item: Union[int, str]) -> CharsetMatch: """ Retrieve a single item either by its position or encoding name (alias may be used here). Raise KeyError upon invalid index or encoding not present in results. """ if isinstance(item, int): return self._results[item] if isinstance(item, str): item = iana_name(item, False) for result in self._results: if item in result.could_be_from_charset: return result raise KeyError def __len__(self) -> int: return len(self._results) def __bool__(self) -> bool: return len(self._results) > 0 def append(self, item: CharsetMatch) -> None: """ Insert a single match. Will be inserted accordingly to preserve sort. Can be inserted as a submatch. """ if not isinstance(item, CharsetMatch): raise ValueError( "Cannot append instance '{}' to CharsetMatches".format( str(item.__class__) ) ) # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage) if len(item.raw) <= TOO_BIG_SEQUENCE: for match in self._results: if match.fingerprint == item.fingerprint and match.chaos == item.chaos: match.add_submatch(item) return self._results.append(item) self._results = sorted(self._results) def best(self) -> Optional["CharsetMatch"]: """ Simply return the first match. Strict equivalent to matches[0]. """ if not self._results: return None return self._results[0] def first(self) -> Optional["CharsetMatch"]: """ Redundant method, call the method best(). Kept for BC reasons. """ return self.best() CoherenceMatch = Tuple[str, float] CoherenceMatches = List[CoherenceMatch] class CliDetectionResult: def __init__( self, path: str, encoding: Optional[str], encoding_aliases: List[str], alternative_encodings: List[str], language: str, alphabets: List[str], has_sig_or_bom: bool, chaos: float, coherence: float, unicode_path: Optional[str], is_preferred: bool, ): self.path = path # type: str self.unicode_path = unicode_path # type: Optional[str] self.encoding = encoding # type: Optional[str] self.encoding_aliases = encoding_aliases # type: List[str] self.alternative_encodings = alternative_encodings # type: List[str] self.language = language # type: str self.alphabets = alphabets # type: List[str] self.has_sig_or_bom = has_sig_or_bom # type: bool self.chaos = chaos # type: float self.coherence = coherence # type: float self.is_preferred = is_preferred # type: bool @property def __dict__(self) -> Dict[str, Any]: # type: ignore return { "path": self.path, "encoding": self.encoding, "encoding_aliases": self.encoding_aliases, "alternative_encodings": self.alternative_encodings, "language": self.language, "alphabets": self.alphabets, "has_sig_or_bom": self.has_sig_or_bom, "chaos": self.chaos, "coherence": self.coherence, "unicode_path": self.unicode_path, "is_preferred": self.is_preferred, } def to_json(self) -> str: return dumps(self.__dict__, ensure_ascii=True, indent=4)
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/models.py
models.py
from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE from collections import OrderedDict from encodings.aliases import aliases from re import IGNORECASE, compile as re_compile from typing import Dict, List, Set, Union from .assets import FREQUENCIES # Contain for each eligible encoding a list of/item bytes SIG/BOM ENCODING_MARKS = OrderedDict( [ ("utf_8", BOM_UTF8), ( "utf_7", [ b"\x2b\x2f\x76\x38", b"\x2b\x2f\x76\x39", b"\x2b\x2f\x76\x2b", b"\x2b\x2f\x76\x2f", b"\x2b\x2f\x76\x38\x2d", ], ), ("gb18030", b"\x84\x31\x95\x33"), ("utf_32", [BOM_UTF32_BE, BOM_UTF32_LE]), ("utf_16", [BOM_UTF16_BE, BOM_UTF16_LE]), ] ) # type: Dict[str, Union[bytes, List[bytes]]] TOO_SMALL_SEQUENCE = 32 # type: int TOO_BIG_SEQUENCE = int(10e6) # type: int UTF8_MAXIMAL_ALLOCATION = 1112064 # type: int UNICODE_RANGES_COMBINED = { "Control character": range(31 + 1), "Basic Latin": range(32, 127 + 1), "Latin-1 Supplement": range(128, 255 + 1), "Latin Extended-A": range(256, 383 + 1), "Latin Extended-B": range(384, 591 + 1), "IPA Extensions": range(592, 687 + 1), "Spacing Modifier Letters": range(688, 767 + 1), "Combining Diacritical Marks": range(768, 879 + 1), "Greek and Coptic": range(880, 1023 + 1), "Cyrillic": range(1024, 1279 + 1), "Cyrillic Supplement": range(1280, 1327 + 1), "Armenian": range(1328, 1423 + 1), "Hebrew": range(1424, 1535 + 1), "Arabic": range(1536, 1791 + 1), "Syriac": range(1792, 1871 + 1), "Arabic Supplement": range(1872, 1919 + 1), "Thaana": range(1920, 1983 + 1), "NKo": range(1984, 2047 + 1), "Samaritan": range(2048, 2111 + 1), "Mandaic": range(2112, 2143 + 1), "Syriac Supplement": range(2144, 2159 + 1), "Arabic Extended-A": range(2208, 2303 + 1), "Devanagari": range(2304, 2431 + 1), "Bengali": range(2432, 2559 + 1), "Gurmukhi": range(2560, 2687 + 1), "Gujarati": range(2688, 2815 + 1), "Oriya": range(2816, 2943 + 1), "Tamil": range(2944, 3071 + 1), "Telugu": range(3072, 3199 + 1), "Kannada": range(3200, 3327 + 1), "Malayalam": range(3328, 3455 + 1), "Sinhala": range(3456, 3583 + 1), "Thai": range(3584, 3711 + 1), "Lao": range(3712, 3839 + 1), "Tibetan": range(3840, 4095 + 1), "Myanmar": range(4096, 4255 + 1), "Georgian": range(4256, 4351 + 1), "Hangul Jamo": range(4352, 4607 + 1), "Ethiopic": range(4608, 4991 + 1), "Ethiopic Supplement": range(4992, 5023 + 1), "Cherokee": range(5024, 5119 + 1), "Unified Canadian Aboriginal Syllabics": range(5120, 5759 + 1), "Ogham": range(5760, 5791 + 1), "Runic": range(5792, 5887 + 1), "Tagalog": range(5888, 5919 + 1), "Hanunoo": range(5920, 5951 + 1), "Buhid": range(5952, 5983 + 1), "Tagbanwa": range(5984, 6015 + 1), "Khmer": range(6016, 6143 + 1), "Mongolian": range(6144, 6319 + 1), "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6399 + 1), "Limbu": range(6400, 6479 + 1), "Tai Le": range(6480, 6527 + 1), "New Tai Lue": range(6528, 6623 + 1), "Khmer Symbols": range(6624, 6655 + 1), "Buginese": range(6656, 6687 + 1), "Tai Tham": range(6688, 6831 + 1), "Combining Diacritical Marks Extended": range(6832, 6911 + 1), "Balinese": range(6912, 7039 + 1), "Sundanese": range(7040, 7103 + 1), "Batak": range(7104, 7167 + 1), "Lepcha": range(7168, 7247 + 1), "Ol Chiki": range(7248, 7295 + 1), "Cyrillic Extended C": range(7296, 7311 + 1), "Sundanese Supplement": range(7360, 7375 + 1), "Vedic Extensions": range(7376, 7423 + 1), "Phonetic Extensions": range(7424, 7551 + 1), "Phonetic Extensions Supplement": range(7552, 7615 + 1), "Combining Diacritical Marks Supplement": range(7616, 7679 + 1), "Latin Extended Additional": range(7680, 7935 + 1), "Greek Extended": range(7936, 8191 + 1), "General Punctuation": range(8192, 8303 + 1), "Superscripts and Subscripts": range(8304, 8351 + 1), "Currency Symbols": range(8352, 8399 + 1), "Combining Diacritical Marks for Symbols": range(8400, 8447 + 1), "Letterlike Symbols": range(8448, 8527 + 1), "Number Forms": range(8528, 8591 + 1), "Arrows": range(8592, 8703 + 1), "Mathematical Operators": range(8704, 8959 + 1), "Miscellaneous Technical": range(8960, 9215 + 1), "Control Pictures": range(9216, 9279 + 1), "Optical Character Recognition": range(9280, 9311 + 1), "Enclosed Alphanumerics": range(9312, 9471 + 1), "Box Drawing": range(9472, 9599 + 1), "Block Elements": range(9600, 9631 + 1), "Geometric Shapes": range(9632, 9727 + 1), "Miscellaneous Symbols": range(9728, 9983 + 1), "Dingbats": range(9984, 10175 + 1), "Miscellaneous Mathematical Symbols-A": range(10176, 10223 + 1), "Supplemental Arrows-A": range(10224, 10239 + 1), "Braille Patterns": range(10240, 10495 + 1), "Supplemental Arrows-B": range(10496, 10623 + 1), "Miscellaneous Mathematical Symbols-B": range(10624, 10751 + 1), "Supplemental Mathematical Operators": range(10752, 11007 + 1), "Miscellaneous Symbols and Arrows": range(11008, 11263 + 1), "Glagolitic": range(11264, 11359 + 1), "Latin Extended-C": range(11360, 11391 + 1), "Coptic": range(11392, 11519 + 1), "Georgian Supplement": range(11520, 11567 + 1), "Tifinagh": range(11568, 11647 + 1), "Ethiopic Extended": range(11648, 11743 + 1), "Cyrillic Extended-A": range(11744, 11775 + 1), "Supplemental Punctuation": range(11776, 11903 + 1), "CJK Radicals Supplement": range(11904, 12031 + 1), "Kangxi Radicals": range(12032, 12255 + 1), "Ideographic Description Characters": range(12272, 12287 + 1), "CJK Symbols and Punctuation": range(12288, 12351 + 1), "Hiragana": range(12352, 12447 + 1), "Katakana": range(12448, 12543 + 1), "Bopomofo": range(12544, 12591 + 1), "Hangul Compatibility Jamo": range(12592, 12687 + 1), "Kanbun": range(12688, 12703 + 1), "Bopomofo Extended": range(12704, 12735 + 1), "CJK Strokes": range(12736, 12783 + 1), "Katakana Phonetic Extensions": range(12784, 12799 + 1), "Enclosed CJK Letters and Months": range(12800, 13055 + 1), "CJK Compatibility": range(13056, 13311 + 1), "CJK Unified Ideographs Extension A": range(13312, 19903 + 1), "Yijing Hexagram Symbols": range(19904, 19967 + 1), "CJK Unified Ideographs": range(19968, 40959 + 1), "Yi Syllables": range(40960, 42127 + 1), "Yi Radicals": range(42128, 42191 + 1), "Lisu": range(42192, 42239 + 1), "Vai": range(42240, 42559 + 1), "Cyrillic Extended-B": range(42560, 42655 + 1), "Bamum": range(42656, 42751 + 1), "Modifier Tone Letters": range(42752, 42783 + 1), "Latin Extended-D": range(42784, 43007 + 1), "Syloti Nagri": range(43008, 43055 + 1), "Common Indic Number Forms": range(43056, 43071 + 1), "Phags-pa": range(43072, 43135 + 1), "Saurashtra": range(43136, 43231 + 1), "Devanagari Extended": range(43232, 43263 + 1), "Kayah Li": range(43264, 43311 + 1), "Rejang": range(43312, 43359 + 1), "Hangul Jamo Extended-A": range(43360, 43391 + 1), "Javanese": range(43392, 43487 + 1), "Myanmar Extended-B": range(43488, 43519 + 1), "Cham": range(43520, 43615 + 1), "Myanmar Extended-A": range(43616, 43647 + 1), "Tai Viet": range(43648, 43743 + 1), "Meetei Mayek Extensions": range(43744, 43775 + 1), "Ethiopic Extended-A": range(43776, 43823 + 1), "Latin Extended-E": range(43824, 43887 + 1), "Cherokee Supplement": range(43888, 43967 + 1), "Meetei Mayek": range(43968, 44031 + 1), "Hangul Syllables": range(44032, 55215 + 1), "Hangul Jamo Extended-B": range(55216, 55295 + 1), "High Surrogates": range(55296, 56191 + 1), "High Private Use Surrogates": range(56192, 56319 + 1), "Low Surrogates": range(56320, 57343 + 1), "Private Use Area": range(57344, 63743 + 1), "CJK Compatibility Ideographs": range(63744, 64255 + 1), "Alphabetic Presentation Forms": range(64256, 64335 + 1), "Arabic Presentation Forms-A": range(64336, 65023 + 1), "Variation Selectors": range(65024, 65039 + 1), "Vertical Forms": range(65040, 65055 + 1), "Combining Half Marks": range(65056, 65071 + 1), "CJK Compatibility Forms": range(65072, 65103 + 1), "Small Form Variants": range(65104, 65135 + 1), "Arabic Presentation Forms-B": range(65136, 65279 + 1), "Halfwidth and Fullwidth Forms": range(65280, 65519 + 1), "Specials": range(65520, 65535 + 1), "Linear B Syllabary": range(65536, 65663 + 1), "Linear B Ideograms": range(65664, 65791 + 1), "Aegean Numbers": range(65792, 65855 + 1), "Ancient Greek Numbers": range(65856, 65935 + 1), "Ancient Symbols": range(65936, 65999 + 1), "Phaistos Disc": range(66000, 66047 + 1), "Lycian": range(66176, 66207 + 1), "Carian": range(66208, 66271 + 1), "Coptic Epact Numbers": range(66272, 66303 + 1), "Old Italic": range(66304, 66351 + 1), "Gothic": range(66352, 66383 + 1), "Old Permic": range(66384, 66431 + 1), "Ugaritic": range(66432, 66463 + 1), "Old Persian": range(66464, 66527 + 1), "Deseret": range(66560, 66639 + 1), "Shavian": range(66640, 66687 + 1), "Osmanya": range(66688, 66735 + 1), "Osage": range(66736, 66815 + 1), "Elbasan": range(66816, 66863 + 1), "Caucasian Albanian": range(66864, 66927 + 1), "Linear A": range(67072, 67455 + 1), "Cypriot Syllabary": range(67584, 67647 + 1), "Imperial Aramaic": range(67648, 67679 + 1), "Palmyrene": range(67680, 67711 + 1), "Nabataean": range(67712, 67759 + 1), "Hatran": range(67808, 67839 + 1), "Phoenician": range(67840, 67871 + 1), "Lydian": range(67872, 67903 + 1), "Meroitic Hieroglyphs": range(67968, 67999 + 1), "Meroitic Cursive": range(68000, 68095 + 1), "Kharoshthi": range(68096, 68191 + 1), "Old South Arabian": range(68192, 68223 + 1), "Old North Arabian": range(68224, 68255 + 1), "Manichaean": range(68288, 68351 + 1), "Avestan": range(68352, 68415 + 1), "Inscriptional Parthian": range(68416, 68447 + 1), "Inscriptional Pahlavi": range(68448, 68479 + 1), "Psalter Pahlavi": range(68480, 68527 + 1), "Old Turkic": range(68608, 68687 + 1), "Old Hungarian": range(68736, 68863 + 1), "Rumi Numeral Symbols": range(69216, 69247 + 1), "Brahmi": range(69632, 69759 + 1), "Kaithi": range(69760, 69839 + 1), "Sora Sompeng": range(69840, 69887 + 1), "Chakma": range(69888, 69967 + 1), "Mahajani": range(69968, 70015 + 1), "Sharada": range(70016, 70111 + 1), "Sinhala Archaic Numbers": range(70112, 70143 + 1), "Khojki": range(70144, 70223 + 1), "Multani": range(70272, 70319 + 1), "Khudawadi": range(70320, 70399 + 1), "Grantha": range(70400, 70527 + 1), "Newa": range(70656, 70783 + 1), "Tirhuta": range(70784, 70879 + 1), "Siddham": range(71040, 71167 + 1), "Modi": range(71168, 71263 + 1), "Mongolian Supplement": range(71264, 71295 + 1), "Takri": range(71296, 71375 + 1), "Ahom": range(71424, 71487 + 1), "Warang Citi": range(71840, 71935 + 1), "Zanabazar Square": range(72192, 72271 + 1), "Soyombo": range(72272, 72367 + 1), "Pau Cin Hau": range(72384, 72447 + 1), "Bhaiksuki": range(72704, 72815 + 1), "Marchen": range(72816, 72895 + 1), "Masaram Gondi": range(72960, 73055 + 1), "Cuneiform": range(73728, 74751 + 1), "Cuneiform Numbers and Punctuation": range(74752, 74879 + 1), "Early Dynastic Cuneiform": range(74880, 75087 + 1), "Egyptian Hieroglyphs": range(77824, 78895 + 1), "Anatolian Hieroglyphs": range(82944, 83583 + 1), "Bamum Supplement": range(92160, 92735 + 1), "Mro": range(92736, 92783 + 1), "Bassa Vah": range(92880, 92927 + 1), "Pahawh Hmong": range(92928, 93071 + 1), "Miao": range(93952, 94111 + 1), "Ideographic Symbols and Punctuation": range(94176, 94207 + 1), "Tangut": range(94208, 100351 + 1), "Tangut Components": range(100352, 101119 + 1), "Kana Supplement": range(110592, 110847 + 1), "Kana Extended-A": range(110848, 110895 + 1), "Nushu": range(110960, 111359 + 1), "Duployan": range(113664, 113823 + 1), "Shorthand Format Controls": range(113824, 113839 + 1), "Byzantine Musical Symbols": range(118784, 119039 + 1), "Musical Symbols": range(119040, 119295 + 1), "Ancient Greek Musical Notation": range(119296, 119375 + 1), "Tai Xuan Jing Symbols": range(119552, 119647 + 1), "Counting Rod Numerals": range(119648, 119679 + 1), "Mathematical Alphanumeric Symbols": range(119808, 120831 + 1), "Sutton SignWriting": range(120832, 121519 + 1), "Glagolitic Supplement": range(122880, 122927 + 1), "Mende Kikakui": range(124928, 125151 + 1), "Adlam": range(125184, 125279 + 1), "Arabic Mathematical Alphabetic Symbols": range(126464, 126719 + 1), "Mahjong Tiles": range(126976, 127023 + 1), "Domino Tiles": range(127024, 127135 + 1), "Playing Cards": range(127136, 127231 + 1), "Enclosed Alphanumeric Supplement": range(127232, 127487 + 1), "Enclosed Ideographic Supplement": range(127488, 127743 + 1), "Miscellaneous Symbols and Pictographs": range(127744, 128511 + 1), "Emoticons range(Emoji)": range(128512, 128591 + 1), "Ornamental Dingbats": range(128592, 128639 + 1), "Transport and Map Symbols": range(128640, 128767 + 1), "Alchemical Symbols": range(128768, 128895 + 1), "Geometric Shapes Extended": range(128896, 129023 + 1), "Supplemental Arrows-C": range(129024, 129279 + 1), "Supplemental Symbols and Pictographs": range(129280, 129535 + 1), "CJK Unified Ideographs Extension B": range(131072, 173791 + 1), "CJK Unified Ideographs Extension C": range(173824, 177983 + 1), "CJK Unified Ideographs Extension D": range(177984, 178207 + 1), "CJK Unified Ideographs Extension E": range(178208, 183983 + 1), "CJK Unified Ideographs Extension F": range(183984, 191471 + 1), "CJK Compatibility Ideographs Supplement": range(194560, 195103 + 1), "Tags": range(917504, 917631 + 1), "Variation Selectors Supplement": range(917760, 917999 + 1), } # type: Dict[str, range] UNICODE_SECONDARY_RANGE_KEYWORD = [ "Supplement", "Extended", "Extensions", "Modifier", "Marks", "Punctuation", "Symbols", "Forms", "Operators", "Miscellaneous", "Drawing", "Block", "Shapes", "Supplemental", "Tags", ] # type: List[str] RE_POSSIBLE_ENCODING_INDICATION = re_compile( r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", IGNORECASE, ) IANA_SUPPORTED = sorted( filter( lambda x: x.endswith("_codec") is False and x not in {"rot_13", "tactis", "mbcs"}, list(set(aliases.values())), ) ) # type: List[str] IANA_SUPPORTED_COUNT = len(IANA_SUPPORTED) # type: int # pre-computed code page that are similar using the function cp_similarity. IANA_SUPPORTED_SIMILAR = { "cp037": ["cp1026", "cp1140", "cp273", "cp500"], "cp1026": ["cp037", "cp1140", "cp273", "cp500"], "cp1125": ["cp866"], "cp1140": ["cp037", "cp1026", "cp273", "cp500"], "cp1250": ["iso8859_2"], "cp1251": ["kz1048", "ptcp154"], "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], "cp1253": ["iso8859_7"], "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], "cp1257": ["iso8859_13"], "cp273": ["cp037", "cp1026", "cp1140", "cp500"], "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], "cp500": ["cp037", "cp1026", "cp1140", "cp273"], "cp850": ["cp437", "cp857", "cp858", "cp865"], "cp857": ["cp850", "cp858", "cp865"], "cp858": ["cp437", "cp850", "cp857", "cp865"], "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], "cp866": ["cp1125"], "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], "iso8859_11": ["tis_620"], "iso8859_13": ["cp1257"], "iso8859_14": [ "iso8859_10", "iso8859_15", "iso8859_16", "iso8859_3", "iso8859_9", "latin_1", ], "iso8859_15": [ "cp1252", "cp1254", "iso8859_10", "iso8859_14", "iso8859_16", "iso8859_3", "iso8859_9", "latin_1", ], "iso8859_16": [ "iso8859_14", "iso8859_15", "iso8859_2", "iso8859_3", "iso8859_9", "latin_1", ], "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], "iso8859_7": ["cp1253"], "iso8859_9": [ "cp1252", "cp1254", "cp1258", "iso8859_10", "iso8859_14", "iso8859_15", "iso8859_16", "iso8859_3", "iso8859_4", "latin_1", ], "kz1048": ["cp1251", "ptcp154"], "latin_1": [ "cp1252", "cp1254", "cp1258", "iso8859_10", "iso8859_14", "iso8859_15", "iso8859_16", "iso8859_3", "iso8859_4", "iso8859_9", ], "mac_iceland": ["mac_roman", "mac_turkish"], "mac_roman": ["mac_iceland", "mac_turkish"], "mac_turkish": ["mac_iceland", "mac_roman"], "ptcp154": ["cp1251", "kz1048"], "tis_620": ["iso8859_11"], } # type: Dict[str, List[str]] CHARDET_CORRESPONDENCE = { "iso2022_kr": "ISO-2022-KR", "iso2022_jp": "ISO-2022-JP", "euc_kr": "EUC-KR", "tis_620": "TIS-620", "utf_32": "UTF-32", "euc_jp": "EUC-JP", "koi8_r": "KOI8-R", "iso8859_1": "ISO-8859-1", "iso8859_2": "ISO-8859-2", "iso8859_5": "ISO-8859-5", "iso8859_6": "ISO-8859-6", "iso8859_7": "ISO-8859-7", "iso8859_8": "ISO-8859-8", "utf_16": "UTF-16", "cp855": "IBM855", "mac_cyrillic": "MacCyrillic", "gb2312": "GB2312", "gb18030": "GB18030", "cp932": "CP932", "cp866": "IBM866", "utf_8": "utf-8", "utf_8_sig": "UTF-8-SIG", "shift_jis": "SHIFT_JIS", "big5": "Big5", "cp1250": "windows-1250", "cp1251": "windows-1251", "cp1252": "Windows-1252", "cp1253": "windows-1253", "cp1255": "windows-1255", "cp1256": "windows-1256", "cp1254": "Windows-1254", "cp949": "CP949", } # type: Dict[str, str] COMMON_SAFE_ASCII_CHARACTERS = { "<", ">", "=", ":", "/", "&", ";", "{", "}", "[", "]", ",", "|", '"', "-", } # type: Set[str] KO_NAMES = {"johab", "cp949", "euc_kr"} # type: Set[str] ZH_NAMES = {"big5", "cp950", "big5hkscs", "hz"} # type: Set[str] NOT_PRINTABLE_PATTERN = re_compile(r"[0-9\W\n\r\t]+") LANGUAGE_SUPPORTED_COUNT = len(FREQUENCIES) # type: int # Logging LEVEL bellow DEBUG TRACE = 5 # type: int
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/constant.py
constant.py
from collections import OrderedDict FREQUENCIES = OrderedDict( [ ( "English", [ "e", "a", "t", "i", "o", "n", "s", "r", "h", "l", "d", "c", "u", "m", "f", "p", "g", "w", "y", "b", "v", "k", "x", "j", "z", "q", ], ), ( "German", [ "e", "n", "i", "r", "s", "t", "a", "d", "h", "u", "l", "g", "o", "c", "m", "b", "f", "k", "w", "z", "p", "v", "ü", "ä", "ö", "j", ], ), ( "French", [ "e", "a", "s", "n", "i", "t", "r", "l", "u", "o", "d", "c", "p", "m", "é", "v", "g", "f", "b", "h", "q", "à", "x", "è", "y", "j", ], ), ( "Dutch", [ "e", "n", "a", "i", "r", "t", "o", "d", "s", "l", "g", "h", "v", "m", "u", "k", "c", "p", "b", "w", "j", "z", "f", "y", "x", "ë", ], ), ( "Italian", [ "e", "i", "a", "o", "n", "l", "t", "r", "s", "c", "d", "u", "p", "m", "g", "v", "f", "b", "z", "h", "q", "è", "à", "k", "y", "ò", ], ), ( "Polish", [ "a", "i", "o", "e", "n", "r", "z", "w", "s", "c", "t", "k", "y", "d", "p", "m", "u", "l", "j", "ł", "g", "b", "h", "ą", "ę", "ó", ], ), ( "Spanish", [ "e", "a", "o", "n", "s", "r", "i", "l", "d", "t", "c", "u", "m", "p", "b", "g", "v", "f", "y", "ó", "h", "q", "í", "j", "z", "á", ], ), ( "Russian", [ "о", "а", "е", "и", "н", "с", "т", "р", "в", "л", "к", "м", "д", "п", "у", "г", "я", "ы", "з", "б", "й", "ь", "ч", "х", "ж", "ц", ], ), ( "Japanese", [ "の", "に", "る", "た", "は", "ー", "と", "し", "を", "で", "て", "が", "い", "ン", "れ", "な", "年", "ス", "っ", "ル", "か", "ら", "あ", "さ", "も", "り", ], ), ( "Portuguese", [ "a", "e", "o", "s", "i", "r", "d", "n", "t", "m", "u", "c", "l", "p", "g", "v", "b", "f", "h", "ã", "q", "é", "ç", "á", "z", "í", ], ), ( "Swedish", [ "e", "a", "n", "r", "t", "s", "i", "l", "d", "o", "m", "k", "g", "v", "h", "f", "u", "p", "ä", "c", "b", "ö", "å", "y", "j", "x", ], ), ( "Chinese", [ "的", "一", "是", "不", "了", "在", "人", "有", "我", "他", "这", "个", "们", "中", "来", "上", "大", "为", "和", "国", "地", "到", "以", "说", "时", "要", "就", "出", "会", ], ), ( "Ukrainian", [ "о", "а", "н", "і", "и", "р", "в", "т", "е", "с", "к", "л", "у", "д", "м", "п", "з", "я", "ь", "б", "г", "й", "ч", "х", "ц", "ї", ], ), ( "Norwegian", [ "e", "r", "n", "t", "a", "s", "i", "o", "l", "d", "g", "k", "m", "v", "f", "p", "u", "b", "h", "å", "y", "j", "ø", "c", "æ", "w", ], ), ( "Finnish", [ "a", "i", "n", "t", "e", "s", "l", "o", "u", "k", "ä", "m", "r", "v", "j", "h", "p", "y", "d", "ö", "g", "c", "b", "f", "w", "z", ], ), ( "Vietnamese", [ "n", "h", "t", "i", "c", "g", "a", "o", "u", "m", "l", "r", "à", "đ", "s", "e", "v", "p", "b", "y", "ư", "d", "á", "k", "ộ", "ế", ], ), ( "Czech", [ "o", "e", "a", "n", "t", "s", "i", "l", "v", "r", "k", "d", "u", "m", "p", "í", "c", "h", "z", "á", "y", "j", "b", "ě", "é", "ř", ], ), ( "Hungarian", [ "e", "a", "t", "l", "s", "n", "k", "r", "i", "o", "z", "á", "é", "g", "m", "b", "y", "v", "d", "h", "u", "p", "j", "ö", "f", "c", ], ), ( "Korean", [ "이", "다", "에", "의", "는", "로", "하", "을", "가", "고", "지", "서", "한", "은", "기", "으", "년", "대", "사", "시", "를", "리", "도", "인", "스", "일", ], ), ( "Indonesian", [ "a", "n", "e", "i", "r", "t", "u", "s", "d", "k", "m", "l", "g", "p", "b", "o", "h", "y", "j", "c", "w", "f", "v", "z", "x", "q", ], ), ( "Turkish", [ "a", "e", "i", "n", "r", "l", "ı", "k", "d", "t", "s", "m", "y", "u", "o", "b", "ü", "ş", "v", "g", "z", "h", "c", "p", "ç", "ğ", ], ), ( "Romanian", [ "e", "i", "a", "r", "n", "t", "u", "l", "o", "c", "s", "d", "p", "m", "ă", "f", "v", "î", "g", "b", "ș", "ț", "z", "h", "â", "j", ], ), ( "Farsi", [ "ا", "ی", "ر", "د", "ن", "ه", "و", "م", "ت", "ب", "س", "ل", "ک", "ش", "ز", "ف", "گ", "ع", "خ", "ق", "ج", "آ", "پ", "ح", "ط", "ص", ], ), ( "Arabic", [ "ا", "ل", "ي", "م", "و", "ن", "ر", "ت", "ب", "ة", "ع", "د", "س", "ف", "ه", "ك", "ق", "أ", "ح", "ج", "ش", "ط", "ص", "ى", "خ", "إ", ], ), ( "Danish", [ "e", "r", "n", "t", "a", "i", "s", "d", "l", "o", "g", "m", "k", "f", "v", "u", "b", "h", "p", "å", "y", "ø", "æ", "c", "j", "w", ], ), ( "Serbian", [ "а", "и", "о", "е", "н", "р", "с", "у", "т", "к", "ј", "в", "д", "м", "п", "л", "г", "з", "б", "a", "i", "e", "o", "n", "ц", "ш", ], ), ( "Lithuanian", [ "i", "a", "s", "o", "r", "e", "t", "n", "u", "k", "m", "l", "p", "v", "d", "j", "g", "ė", "b", "y", "ų", "š", "ž", "c", "ą", "į", ], ), ( "Slovene", [ "e", "a", "i", "o", "n", "r", "s", "l", "t", "j", "v", "k", "d", "p", "m", "u", "z", "b", "g", "h", "č", "c", "š", "ž", "f", "y", ], ), ( "Slovak", [ "o", "a", "e", "n", "i", "r", "v", "t", "s", "l", "k", "d", "m", "p", "u", "c", "h", "j", "b", "z", "á", "y", "ý", "í", "č", "é", ], ), ( "Hebrew", [ "י", "ו", "ה", "ל", "ר", "ב", "ת", "מ", "א", "ש", "נ", "ע", "ם", "ד", "ק", "ח", "פ", "ס", "כ", "ג", "ט", "צ", "ן", "ז", "ך", ], ), ( "Bulgarian", [ "а", "и", "о", "е", "н", "т", "р", "с", "в", "л", "к", "д", "п", "м", "з", "г", "я", "ъ", "у", "б", "ч", "ц", "й", "ж", "щ", "х", ], ), ( "Croatian", [ "a", "i", "o", "e", "n", "r", "j", "s", "t", "u", "k", "l", "v", "d", "m", "p", "g", "z", "b", "c", "č", "h", "š", "ž", "ć", "f", ], ), ( "Hindi", [ "क", "र", "स", "न", "त", "म", "ह", "प", "य", "ल", "व", "ज", "द", "ग", "ब", "श", "ट", "अ", "ए", "थ", "भ", "ड", "च", "ध", "ष", "इ", ], ), ( "Estonian", [ "a", "i", "e", "s", "t", "l", "u", "n", "o", "k", "r", "d", "m", "v", "g", "p", "j", "h", "ä", "b", "õ", "ü", "f", "c", "ö", "y", ], ), ( "Simple English", [ "e", "a", "t", "i", "o", "n", "s", "r", "h", "l", "d", "c", "m", "u", "f", "p", "g", "w", "b", "y", "v", "k", "j", "x", "z", "q", ], ), ( "Thai", [ "า", "น", "ร", "อ", "ก", "เ", "ง", "ม", "ย", "ล", "ว", "ด", "ท", "ส", "ต", "ะ", "ป", "บ", "ค", "ห", "แ", "จ", "พ", "ช", "ข", "ใ", ], ), ( "Greek", [ "α", "τ", "ο", "ι", "ε", "ν", "ρ", "σ", "κ", "η", "π", "ς", "υ", "μ", "λ", "ί", "ό", "ά", "γ", "έ", "δ", "ή", "ω", "χ", "θ", "ύ", ], ), ( "Tamil", [ "க", "த", "ப", "ட", "ர", "ம", "ல", "ன", "வ", "ற", "ய", "ள", "ச", "ந", "இ", "ண", "அ", "ஆ", "ழ", "ங", "எ", "உ", "ஒ", "ஸ", ], ), ( "Classical Chinese", [ "之", "年", "為", "也", "以", "一", "人", "其", "者", "國", "有", "二", "十", "於", "曰", "三", "不", "大", "而", "子", "中", "五", "四", ], ), ( "Kazakh", [ "а", "ы", "е", "н", "т", "р", "л", "і", "д", "с", "м", "қ", "к", "о", "б", "и", "у", "ғ", "ж", "ң", "з", "ш", "й", "п", "г", "ө", ], ), ] )
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/assets/__init__.py
__init__.py
import argparse import sys from json import dumps from os.path import abspath from platform import python_version from typing import List from charset_normalizer import from_fp from charset_normalizer.models import CliDetectionResult from charset_normalizer.version import __version__ def query_yes_no(question: str, default: str = "yes") -> bool: """Ask a yes/no question via input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". Credit goes to (c) https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == "": return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") def cli_detect(argv: List[str] = None) -> int: """ CLI assistant using ARGV and ArgumentParser :param argv: :return: 0 if everything is fine, anything else equal trouble """ parser = argparse.ArgumentParser( description="The Real First Universal Charset Detector. " "Discover originating encoding used on text file. " "Normalize text to unicode." ) parser.add_argument( "files", type=argparse.FileType("rb"), nargs="+", help="File(s) to be analysed" ) parser.add_argument( "-v", "--verbose", action="store_true", default=False, dest="verbose", help="Display complementary information about file if any. " "Stdout will contain logs about the detection process.", ) parser.add_argument( "-a", "--with-alternative", action="store_true", default=False, dest="alternatives", help="Output complementary possibilities if any. Top-level JSON WILL be a list.", ) parser.add_argument( "-n", "--normalize", action="store_true", default=False, dest="normalize", help="Permit to normalize input file. If not set, program does not write anything.", ) parser.add_argument( "-m", "--minimal", action="store_true", default=False, dest="minimal", help="Only output the charset detected to STDOUT. Disabling JSON output.", ) parser.add_argument( "-r", "--replace", action="store_true", default=False, dest="replace", help="Replace file when trying to normalize it instead of creating a new one.", ) parser.add_argument( "-f", "--force", action="store_true", default=False, dest="force", help="Replace file without asking if you are sure, use this flag with caution.", ) parser.add_argument( "-t", "--threshold", action="store", default=0.1, type=float, dest="threshold", help="Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1.", ) parser.add_argument( "--version", action="version", version="Charset-Normalizer {} - Python {}".format( __version__, python_version() ), help="Show version information and exit.", ) args = parser.parse_args(argv) if args.replace is True and args.normalize is False: print("Use --replace in addition of --normalize only.", file=sys.stderr) return 1 if args.force is True and args.replace is False: print("Use --force in addition of --replace only.", file=sys.stderr) return 1 if args.threshold < 0.0 or args.threshold > 1.0: print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr) return 1 x_ = [] for my_file in args.files: matches = from_fp(my_file, threshold=args.threshold, explain=args.verbose) best_guess = matches.best() if best_guess is None: print( 'Unable to identify originating encoding for "{}". {}'.format( my_file.name, "Maybe try increasing maximum amount of chaos." if args.threshold < 1.0 else "", ), file=sys.stderr, ) x_.append( CliDetectionResult( abspath(my_file.name), None, [], [], "Unknown", [], False, 1.0, 0.0, None, True, ) ) else: x_.append( CliDetectionResult( abspath(my_file.name), best_guess.encoding, best_guess.encoding_aliases, [ cp for cp in best_guess.could_be_from_charset if cp != best_guess.encoding ], best_guess.language, best_guess.alphabets, best_guess.bom, best_guess.percent_chaos, best_guess.percent_coherence, None, True, ) ) if len(matches) > 1 and args.alternatives: for el in matches: if el != best_guess: x_.append( CliDetectionResult( abspath(my_file.name), el.encoding, el.encoding_aliases, [ cp for cp in el.could_be_from_charset if cp != el.encoding ], el.language, el.alphabets, el.bom, el.percent_chaos, el.percent_coherence, None, False, ) ) if args.normalize is True: if best_guess.encoding.startswith("utf") is True: print( '"{}" file does not need to be normalized, as it already came from unicode.'.format( my_file.name ), file=sys.stderr, ) if my_file.closed is False: my_file.close() continue o_ = my_file.name.split(".") # type: List[str] if args.replace is False: o_.insert(-1, best_guess.encoding) if my_file.closed is False: my_file.close() elif ( args.force is False and query_yes_no( 'Are you sure to normalize "{}" by replacing it ?'.format( my_file.name ), "no", ) is False ): if my_file.closed is False: my_file.close() continue try: x_[0].unicode_path = abspath("./{}".format(".".join(o_))) with open(x_[0].unicode_path, "w", encoding="utf-8") as fp: fp.write(str(best_guess)) except IOError as e: print(str(e), file=sys.stderr) if my_file.closed is False: my_file.close() return 2 if my_file.closed is False: my_file.close() if args.minimal is False: print( dumps( [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__, ensure_ascii=True, indent=4, ) ) else: for my_file in args.files: print( ", ".join( [ el.encoding or "undefined" for el in x_ if el.path == abspath(my_file.name) ] ) ) return 0 if __name__ == "__main__": cli_detect()
zdppy-requests
/zdppy_requests-0.1.3-py3-none-any.whl/zdppy_requests/charset_normalizer/cli/normalizer.py
normalizer.py
import datetime import re import sys from decimal import Decimal from .decoder import InlineTableDict if sys.version_info >= (3,): unicode = str def dump(o, f, encoder=None): """Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored encoder: The ``TomlEncoder`` to use for constructing the output string Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is passed """ if not f.write: raise TypeError("You can only dump an object to a file descriptor") d = dumps(o, encoder=encoder) f.write(d) return d def dumps(o, encoder=None): """Stringifies input dict as toml Args: o: Object to dump into toml encoder: The ``TomlEncoder`` to use for constructing the output string Returns: String containing the toml corresponding to dict Examples: ```python >>> import toml >>> output = { ... 'a': "I'm a string", ... 'b': ["I'm", "a", "list"], ... 'c': 2400 ... } >>> toml.dumps(output) 'a = "I\'m a string"\nb = [ "I\'m", "a", "list",]\nc = 2400\n' ``` """ retval = "" if encoder is None: encoder = TomlEncoder(o.__class__) addtoretval, sections = encoder.dump_sections(o, "") retval += addtoretval outer_objs = [id(o)] while sections: section_ids = [id(section) for section in sections.values()] for outer_obj in outer_objs: if outer_obj in section_ids: raise ValueError("Circular reference detected") outer_objs += section_ids newsections = encoder.get_empty_table() for section in sections: addtoretval, addtosections = encoder.dump_sections( sections[section], section) if addtoretval or (not addtoretval and not addtosections): if retval and retval[-2:] != "\n\n": retval += "\n" retval += "[" + section + "]\n" if addtoretval: retval += addtoretval for s in addtosections: newsections[section + "." + s] = addtosections[s] sections = newsections return retval def _dump_str(v): if sys.version_info < (3,) and hasattr(v, 'decode') and isinstance(v, str): v = v.decode('utf-8') v = "%r" % v if v[0] == 'u': v = v[1:] singlequote = v.startswith("'") if singlequote or v.startswith('"'): v = v[1:-1] if singlequote: v = v.replace("\\'", "'") v = v.replace('"', '\\"') v = v.split("\\x") while len(v) > 1: i = -1 if not v[0]: v = v[1:] v[0] = v[0].replace("\\\\", "\\") # No, I don't know why != works and == breaks joinx = v[0][i] != "\\" while v[0][:i] and v[0][i] == "\\": joinx = not joinx i -= 1 if joinx: joiner = "x" else: joiner = "u00" v = [v[0] + joiner + v[1]] + v[2:] return unicode('"' + v[0] + '"') def _dump_float(v): return "{}".format(v).replace("e+0", "e+").replace("e-0", "e-") def _dump_time(v): utcoffset = v.utcoffset() if utcoffset is None: return v.isoformat() # The TOML norm specifies that it's local time thus we drop the offset return v.isoformat()[:-6] class TomlEncoder(object): def __init__(self, _dict=dict, preserve=False): self._dict = _dict self.preserve = preserve self.dump_funcs = { str: _dump_str, unicode: _dump_str, list: self.dump_list, bool: lambda v: unicode(v).lower(), int: lambda v: v, float: _dump_float, Decimal: _dump_float, datetime.datetime: lambda v: v.isoformat().replace('+00:00', 'Z'), datetime.time: _dump_time, datetime.date: lambda v: v.isoformat() } def get_empty_table(self): return self._dict() def dump_list(self, v): retval = "[" for u in v: retval += " " + unicode(self.dump_value(u)) + "," retval += "]" return retval def dump_inline_table(self, section): """Preserve inline table in its compact syntax instead of expanding into subsection. https://github.com/toml-lang/toml#user-content-inline-table """ retval = "" if isinstance(section, dict): val_list = [] for k, v in section.items(): val = self.dump_inline_table(v) val_list.append(k + " = " + val) retval += "{ " + ", ".join(val_list) + " }\n" return retval else: return unicode(self.dump_value(section)) def dump_value(self, v): # Lookup function corresponding to v's type dump_fn = self.dump_funcs.get(type(v)) if dump_fn is None and hasattr(v, '__iter__'): dump_fn = self.dump_funcs[list] # Evaluate function (if it exists) else return v return dump_fn(v) if dump_fn is not None else self.dump_funcs[str](v) def dump_sections(self, o, sup): retstr = "" if sup != "" and sup[-1] != ".": sup += '.' retdict = self._dict() arraystr = "" for section in o: section = unicode(section) qsection = section if not re.match(r'^[A-Za-z0-9_-]+$', section): qsection = _dump_str(section) if not isinstance(o[section], dict): arrayoftables = False if isinstance(o[section], list): for a in o[section]: if isinstance(a, dict): arrayoftables = True if arrayoftables: for a in o[section]: arraytabstr = "\n" arraystr += "[[" + sup + qsection + "]]\n" s, d = self.dump_sections(a, sup + qsection) if s: if s[0] == "[": arraytabstr += s else: arraystr += s while d: newd = self._dict() for dsec in d: s1, d1 = self.dump_sections(d[dsec], sup + qsection + "." + dsec) if s1: arraytabstr += ("[" + sup + qsection + "." + dsec + "]\n") arraytabstr += s1 for s1 in d1: newd[dsec + "." + s1] = d1[s1] d = newd arraystr += arraytabstr else: if o[section] is not None: retstr += (qsection + " = " + unicode(self.dump_value(o[section])) + '\n') elif self.preserve and isinstance(o[section], InlineTableDict): retstr += (qsection + " = " + self.dump_inline_table(o[section])) else: retdict[qsection] = o[section] retstr += arraystr return (retstr, retdict) class TomlPreserveInlineDictEncoder(TomlEncoder): def __init__(self, _dict=dict): super(TomlPreserveInlineDictEncoder, self).__init__(_dict, True) class TomlArraySeparatorEncoder(TomlEncoder): def __init__(self, _dict=dict, preserve=False, separator=","): super(TomlArraySeparatorEncoder, self).__init__(_dict, preserve) if separator.strip() == "": separator = "," + separator elif separator.strip(' \t\n\r,'): raise ValueError("Invalid separator for arrays") self.separator = separator def dump_list(self, v): t = [] retval = "[" for u in v: t.append(self.dump_value(u)) while t != []: s = [] for u in t: if isinstance(u, list): for r in u: s.append(r) else: retval += " " + unicode(u) + self.separator t = s retval += "]" return retval class TomlNumpyEncoder(TomlEncoder): def __init__(self, _dict=dict, preserve=False): import numpy as np super(TomlNumpyEncoder, self).__init__(_dict, preserve) self.dump_funcs[np.float16] = _dump_float self.dump_funcs[np.float32] = _dump_float self.dump_funcs[np.float64] = _dump_float self.dump_funcs[np.int16] = self._dump_int self.dump_funcs[np.int32] = self._dump_int self.dump_funcs[np.int64] = self._dump_int def _dump_int(self, v): return "{}".format(int(v)) class TomlPreserveCommentEncoder(TomlEncoder): def __init__(self, _dict=dict, preserve=False): from toml.decoder import CommentValue super(TomlPreserveCommentEncoder, self).__init__(_dict, preserve) self.dump_funcs[CommentValue] = lambda v: v.dump(self.dump_value) class TomlPathlibEncoder(TomlEncoder): def _dump_pathlib_path(self, v): return _dump_str(str(v)) def dump_value(self, v): if (3, 4) <= sys.version_info: import pathlib if isinstance(v, pathlib.PurePath): v = str(v) return super(TomlPathlibEncoder, self).dump_value(v)
zdppy-toml
/zdppy_toml-0.1.0.tar.gz/zdppy_toml-0.1.0/zdppy_toml/libs/toml/encoder.py
encoder.py
import datetime import io from os import linesep import re import sys from toml.tz import TomlTz # 兼容python2的写法 if sys.version_info < (3,): _range = xrange # noqa: F821 else: unicode = str _range = range basestring = str unichr = chr def _detect_pathlib_path(p): if (3, 4) <= sys.version_info: import pathlib if isinstance(p, pathlib.PurePath): return True return False def _ispath(p): if isinstance(p, (bytes, basestring)): return True return _detect_pathlib_path(p) def _getpath(p): if (3, 6) <= sys.version_info: import os return os.fspath(p) if _detect_pathlib_path(p): return str(p) return p try: FNFError = FileNotFoundError except NameError: FNFError = IOError TIME_RE = re.compile(r"([0-9]{2}):([0-9]{2}):([0-9]{2})(\.([0-9]{3,6}))?") class TomlDecodeError(ValueError): """Base toml Exception / Error.""" def __init__(self, msg, doc, pos): lineno = doc.count('\n', 0, pos) + 1 colno = pos - doc.rfind('\n', 0, pos) emsg = '{} (line {} column {} char {})'.format(msg, lineno, colno, pos) ValueError.__init__(self, emsg) self.msg = msg self.doc = doc self.pos = pos self.lineno = lineno self.colno = colno # Matches a TOML number, which allows underscores for readability _number_with_underscores = re.compile('([0-9])(_([0-9]))*') class CommentValue(object): def __init__(self, val, comment, beginline, _dict): self.val = val separator = "\n" if beginline else " " self.comment = separator + comment self._dict = _dict def __getitem__(self, key): return self.val[key] def __setitem__(self, key, value): self.val[key] = value def dump(self, dump_value_func): retstr = dump_value_func(self.val) if isinstance(self.val, self._dict): return self.comment + "\n" + unicode(retstr) else: return unicode(retstr) + self.comment def _strictly_valid_num(n): n = n.strip() if not n: return False if n[0] == '_': return False if n[-1] == '_': return False if "_." in n or "._" in n: return False if len(n) == 1: return True if n[0] == '0' and n[1] not in ['.', 'o', 'b', 'x']: return False if n[0] == '+' or n[0] == '-': n = n[1:] if len(n) > 1 and n[0] == '0' and n[1] != '.': return False if '__' in n: return False return True def load(f, _dict=dict, decoder=None): """Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary decoder: The decoder to use Returns: Parsed toml file represented as a dictionary Raises: TypeError -- When f is invalid type TomlDecodeError: Error while decoding toml IOError / FileNotFoundError -- When an array with no valid (existing) (Python 2 / Python 3) file paths is passed """ if _ispath(f): with io.open(_getpath(f), encoding='utf-8') as ffile: return loads(ffile.read(), _dict, decoder) elif isinstance(f, list): from os import path as op from warnings import warn if not [path for path in f if op.exists(path)]: error_msg = "Load expects a list to contain filenames only." error_msg += linesep error_msg += ("The list needs to contain the path of at least one " "existing file.") raise FNFError(error_msg) if decoder is None: decoder = TomlDecoder(_dict) d = decoder.get_empty_table() for l in f: # noqa: E741 if op.exists(l): d.update(load(l, _dict, decoder)) else: warn("Non-existent filename in list with at least one valid " "filename") return d else: try: return loads(f.read(), _dict, decoder) except AttributeError: raise TypeError("You can only load a file descriptor, filename or " "list") _groupname_re = re.compile(r'^[A-Za-z0-9_-]+$') def loads(s, _dict=dict, decoder=None): """Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed TomlDecodeError: Error while decoding toml """ implicitgroups = [] if decoder is None: decoder = TomlDecoder(_dict) retval = decoder.get_empty_table() currentlevel = retval if not isinstance(s, basestring): raise TypeError("Expecting something like a string") if not isinstance(s, unicode): s = s.decode('utf8') original = s sl = list(s) openarr = 0 openstring = False openstrchar = "" multilinestr = False arrayoftables = False beginline = True keygroup = False dottedkey = False keyname = 0 key = '' prev_key = '' line_no = 1 for i, item in enumerate(sl): if item == '\r' and sl[i + 1] == '\n': sl[i] = ' ' continue if keyname: key += item if item == '\n': raise TomlDecodeError("Key name found without value." " Reached end of line.", original, i) if openstring: if item == openstrchar: oddbackslash = False k = 1 while i >= k and sl[i - k] == '\\': oddbackslash = not oddbackslash k += 1 if not oddbackslash: keyname = 2 openstring = False openstrchar = "" continue elif keyname == 1: if item.isspace(): keyname = 2 continue elif item == '.': dottedkey = True continue elif item.isalnum() or item == '_' or item == '-': continue elif (dottedkey and sl[i - 1] == '.' and (item == '"' or item == "'")): openstring = True openstrchar = item continue elif keyname == 2: if item.isspace(): if dottedkey: nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '.': dottedkey = True nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '=': keyname = 0 prev_key = key[:-1].rstrip() key = '' dottedkey = False else: raise TomlDecodeError("Found invalid character in key name: '" + item + "'. Try quoting the key name.", original, i) if item == "'" and openstrchar != '"': k = 1 try: while sl[i - k] == "'": k += 1 if k == 3: break except IndexError: pass if k == 3: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = "'" else: openstrchar = "" if item == '"' and openstrchar != "'": oddbackslash = False k = 1 tripquote = False try: while sl[i - k] == '"': k += 1 if k == 3: tripquote = True break if k == 1 or (k == 3 and tripquote): while sl[i - k] == '\\': oddbackslash = not oddbackslash k += 1 except IndexError: pass if not oddbackslash: if tripquote: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = '"' else: openstrchar = "" if item == '#' and (not openstring and not keygroup and not arrayoftables): j = i comment = "" try: while sl[j] != '\n': comment += s[j] sl[j] = ' ' j += 1 except IndexError: break if not openarr: decoder.preserve_comment(line_no, prev_key, comment, beginline) if item == '[' and (not openstring and not keygroup and not arrayoftables): if beginline: if len(sl) > i + 1 and sl[i + 1] == '[': arrayoftables = True else: keygroup = True else: openarr += 1 if item == ']' and not openstring: if keygroup: keygroup = False elif arrayoftables: if sl[i - 1] == ']': arrayoftables = False else: openarr -= 1 if item == '\n': if openstring or multilinestr: if not multilinestr: raise TomlDecodeError("Unbalanced quotes", original, i) if ((sl[i - 1] == "'" or sl[i - 1] == '"') and ( sl[i - 2] == sl[i - 1])): sl[i] = sl[i - 1] if sl[i - 3] == sl[i - 1]: sl[i - 3] = ' ' elif openarr: sl[i] = ' ' else: beginline = True line_no += 1 elif beginline and sl[i] != ' ' and sl[i] != '\t': beginline = False if not keygroup and not arrayoftables: if sl[i] == '=': raise TomlDecodeError("Found empty keyname. ", original, i) keyname = 1 key += item if keyname: raise TomlDecodeError("Key name found without value." " Reached end of file.", original, len(s)) if openstring: # reached EOF and have an unterminated string raise TomlDecodeError("Unterminated string found." " Reached end of file.", original, len(s)) s = ''.join(sl) s = s.split('\n') multikey = None multilinestr = "" multibackslash = False pos = 0 for idx, line in enumerate(s): if idx > 0: pos += len(s[idx - 1]) + 1 decoder.embed_comments(idx, currentlevel) if not multilinestr or multibackslash or '\n' not in multilinestr: line = line.strip() if line == "" and (not multikey or multibackslash): continue if multikey: if multibackslash: multilinestr += line else: multilinestr += line multibackslash = False closed = False if multilinestr[0] == '[': closed = line[-1] == ']' elif len(line) > 2: closed = (line[-1] == multilinestr[0] and line[-2] == multilinestr[0] and line[-3] == multilinestr[0]) if closed: try: value, vtype = decoder.load_value(multilinestr) except ValueError as err: raise TomlDecodeError(str(err), original, pos) currentlevel[multikey] = value multikey = None multilinestr = "" else: k = len(multilinestr) - 1 while k > -1 and multilinestr[k] == '\\': multibackslash = not multibackslash k -= 1 if multibackslash: multilinestr = multilinestr[:-1] else: multilinestr += "\n" continue if line[0] == '[': arrayoftables = False if len(line) == 1: raise TomlDecodeError("Opening key group bracket on line by " "itself.", original, pos) if line[1] == '[': arrayoftables = True line = line[2:] splitstr = ']]' else: line = line[1:] splitstr = ']' i = 1 quotesplits = decoder._get_split_on_quotes(line) quoted = False for quotesplit in quotesplits: if not quoted and splitstr in quotesplit: break i += quotesplit.count(splitstr) quoted = not quoted line = line.split(splitstr, i) if len(line) < i + 1 or line[-1].strip() != "": raise TomlDecodeError("Key group not on a line by itself.", original, pos) groups = splitstr.join(line[:-1]).split('.') i = 0 while i < len(groups): groups[i] = groups[i].strip() if len(groups[i]) > 0 and (groups[i][0] == '"' or groups[i][0] == "'"): groupstr = groups[i] j = i + 1 while ((not groupstr[0] == groupstr[-1]) or len(groupstr) == 1): j += 1 if j > len(groups) + 2: raise TomlDecodeError("Invalid group name '" + groupstr + "' Something " + "went wrong.", original, pos) groupstr = '.'.join(groups[i:j]).strip() groups[i] = groupstr[1:-1] groups[i + 1:j] = [] else: if not _groupname_re.match(groups[i]): raise TomlDecodeError("Invalid group name '" + groups[i] + "'. Try quoting it.", original, pos) i += 1 currentlevel = retval for i in _range(len(groups)): group = groups[i] if group == "": raise TomlDecodeError("Can't have a keygroup with an empty " "name", original, pos) try: currentlevel[group] if i == len(groups) - 1: if group in implicitgroups: implicitgroups.remove(group) if arrayoftables: raise TomlDecodeError("An implicitly defined " "table can't be an array", original, pos) elif arrayoftables: currentlevel[group].append(decoder.get_empty_table() ) else: raise TomlDecodeError("What? " + group + " already exists?" + str(currentlevel), original, pos) except TypeError: currentlevel = currentlevel[-1] if group not in currentlevel: currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] except KeyError: if i != len(groups) - 1: implicitgroups.append(group) currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] currentlevel = currentlevel[group] if arrayoftables: try: currentlevel = currentlevel[-1] except KeyError: pass elif line[0] == "{": if line[-1] != "}": raise TomlDecodeError("Line breaks are not allowed in inline" "objects", original, pos) try: decoder.load_inline_object(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) elif "=" in line: try: ret = decoder.load_line(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) if ret is not None: multikey, multilinestr, multibackslash = ret return retval def _load_date(val): microsecond = 0 tz = None try: if len(val) > 19: if val[19] == '.': if val[-1].upper() == 'Z': subsecondval = val[20:-1] tzval = "Z" else: subsecondvalandtz = val[20:] if '+' in subsecondvalandtz: splitpoint = subsecondvalandtz.index('+') subsecondval = subsecondvalandtz[:splitpoint] tzval = subsecondvalandtz[splitpoint:] elif '-' in subsecondvalandtz: splitpoint = subsecondvalandtz.index('-') subsecondval = subsecondvalandtz[:splitpoint] tzval = subsecondvalandtz[splitpoint:] else: tzval = None subsecondval = subsecondvalandtz if tzval is not None: tz = TomlTz(tzval) microsecond = int(int(subsecondval) * (10 ** (6 - len(subsecondval)))) else: tz = TomlTz(val[19:]) except ValueError: tz = None if "-" not in val[1:]: return None try: if len(val) == 10: d = datetime.date( int(val[:4]), int(val[5:7]), int(val[8:10])) else: d = datetime.datetime( int(val[:4]), int(val[5:7]), int(val[8:10]), int(val[11:13]), int(val[14:16]), int(val[17:19]), microsecond, tz) except ValueError: return None return d def _load_unicode_escapes(v, hexbytes, prefix): skip = False i = len(v) - 1 while i > -1 and v[i] == '\\': skip = not skip i -= 1 for hx in hexbytes: if skip: skip = False i = len(hx) - 1 while i > -1 and hx[i] == '\\': skip = not skip i -= 1 v += prefix v += hx continue hxb = "" i = 0 hxblen = 4 if prefix == "\\U": hxblen = 8 hxb = ''.join(hx[i:i + hxblen]).lower() if hxb.strip('0123456789abcdef'): raise ValueError("Invalid escape sequence: " + hxb) if hxb[0] == "d" and hxb[1].strip('01234567'): raise ValueError("Invalid escape sequence: " + hxb + ". Only scalar unicode points are allowed.") v += unichr(int(hxb, 16)) v += unicode(hx[len(hxb):]) return v # Unescape TOML string values. # content after the \ _escapes = ['0', 'b', 'f', 'n', 'r', 't', '"'] # What it should be replaced by _escapedchars = ['\0', '\b', '\f', '\n', '\r', '\t', '\"'] # Used for substitution _escape_to_escapedchars = dict(zip(_escapes, _escapedchars)) def _unescape(v): """Unescape characters in a TOML string.""" i = 0 backslash = False while i < len(v): if backslash: backslash = False if v[i] in _escapes: v = v[:i - 1] + _escape_to_escapedchars[v[i]] + v[i + 1:] elif v[i] == '\\': v = v[:i - 1] + v[i:] elif v[i] == 'u' or v[i] == 'U': i += 1 else: raise ValueError("Reserved escape sequence used") continue elif v[i] == '\\': backslash = True i += 1 return v class InlineTableDict(object): """Sentinel subclass of dict for inline tables.""" class TomlDecoder(object): def __init__(self, _dict=dict): self._dict = _dict def get_empty_table(self): return self._dict() def get_empty_inline_table(self): class DynamicInlineTableDict(self._dict, InlineTableDict): """Concrete sentinel subclass for inline tables. It is a subclass of _dict which is passed in dynamically at load time It is also a subclass of InlineTableDict """ return DynamicInlineTableDict() def load_inline_object(self, line, currentlevel, multikey=False, multibackslash=False): candidate_groups = line[1:-1].split(",") groups = [] if len(candidate_groups) == 1 and not candidate_groups[0].strip(): candidate_groups.pop() while len(candidate_groups) > 0: candidate_group = candidate_groups.pop(0) try: _, value = candidate_group.split('=', 1) except ValueError: raise ValueError("Invalid inline table encountered") value = value.strip() if ((value[0] == value[-1] and value[0] in ('"', "'")) or ( value[0] in '-0123456789' or value in ('true', 'false') or (value[0] == "[" and value[-1] == "]") or (value[0] == '{' and value[-1] == '}'))): groups.append(candidate_group) elif len(candidate_groups) > 0: candidate_groups[0] = (candidate_group + "," + candidate_groups[0]) else: raise ValueError("Invalid inline table value encountered") for group in groups: status = self.load_line(group, currentlevel, multikey, multibackslash) if status is not None: break def _get_split_on_quotes(self, line): doublequotesplits = line.split('"') quoted = False quotesplits = [] if len(doublequotesplits) > 1 and "'" in doublequotesplits[0]: singlequotesplits = doublequotesplits[0].split("'") doublequotesplits = doublequotesplits[1:] while len(singlequotesplits) % 2 == 0 and len(doublequotesplits): singlequotesplits[-1] += '"' + doublequotesplits[0] doublequotesplits = doublequotesplits[1:] if "'" in singlequotesplits[-1]: singlequotesplits = (singlequotesplits[:-1] + singlequotesplits[-1].split("'")) quotesplits += singlequotesplits for doublequotesplit in doublequotesplits: if quoted: quotesplits.append(doublequotesplit) else: quotesplits += doublequotesplit.split("'") quoted = not quoted return quotesplits def load_line(self, line, currentlevel, multikey, multibackslash): i = 1 quotesplits = self._get_split_on_quotes(line) quoted = False for quotesplit in quotesplits: if not quoted and '=' in quotesplit: break i += quotesplit.count('=') quoted = not quoted pair = line.split('=', i) strictly_valid = _strictly_valid_num(pair[-1]) if _number_with_underscores.match(pair[-1]): pair[-1] = pair[-1].replace('_', '') while len(pair[-1]) and (pair[-1][0] != ' ' and pair[-1][0] != '\t' and pair[-1][0] != "'" and pair[-1][0] != '"' and pair[-1][0] != '[' and pair[-1][0] != '{' and pair[-1].strip() != 'true' and pair[-1].strip() != 'false'): try: float(pair[-1]) break except ValueError: pass if _load_date(pair[-1]) is not None: break if TIME_RE.match(pair[-1]): break i += 1 prev_val = pair[-1] pair = line.split('=', i) if prev_val == pair[-1]: raise ValueError("Invalid date or number") if strictly_valid: strictly_valid = _strictly_valid_num(pair[-1]) pair = ['='.join(pair[:-1]).strip(), pair[-1].strip()] if '.' in pair[0]: if '"' in pair[0] or "'" in pair[0]: quotesplits = self._get_split_on_quotes(pair[0]) quoted = False levels = [] for quotesplit in quotesplits: if quoted: levels.append(quotesplit) else: levels += [level.strip() for level in quotesplit.split('.')] quoted = not quoted else: levels = pair[0].split('.') while levels[-1] == "": levels = levels[:-1] for level in levels[:-1]: if level == "": continue if level not in currentlevel: currentlevel[level] = self.get_empty_table() currentlevel = currentlevel[level] pair[0] = levels[-1].strip() elif (pair[0][0] == '"' or pair[0][0] == "'") and \ (pair[0][-1] == pair[0][0]): pair[0] = _unescape(pair[0][1:-1]) k, koffset = self._load_line_multiline_str(pair[1]) if k > -1: while k > -1 and pair[1][k + koffset] == '\\': multibackslash = not multibackslash k -= 1 if multibackslash: multilinestr = pair[1][:-1] else: multilinestr = pair[1] + "\n" multikey = pair[0] else: value, vtype = self.load_value(pair[1], strictly_valid) try: currentlevel[pair[0]] raise ValueError("Duplicate keys!") except TypeError: raise ValueError("Duplicate keys!") except KeyError: if multikey: return multikey, multilinestr, multibackslash else: currentlevel[pair[0]] = value def _load_line_multiline_str(self, p): poffset = 0 if len(p) < 3: return -1, poffset if p[0] == '[' and (p.strip()[-1] != ']' and self._load_array_isstrarray(p)): newp = p[1:].strip().split(',') while len(newp) > 1 and newp[-1][0] != '"' and newp[-1][0] != "'": newp = newp[:-2] + [newp[-2] + ',' + newp[-1]] newp = newp[-1] poffset = len(p) - len(newp) p = newp if p[0] != '"' and p[0] != "'": return -1, poffset if p[1] != p[0] or p[2] != p[0]: return -1, poffset if len(p) > 5 and p[-1] == p[0] and p[-2] == p[0] and p[-3] == p[0]: return -1, poffset return len(p) - 1, poffset def load_value(self, v, strictly_valid=True): if not v: raise ValueError("Empty value is invalid") if v == 'true': return (True, "bool") elif v.lower() == 'true': raise ValueError("Only all lowercase booleans allowed") elif v == 'false': return (False, "bool") elif v.lower() == 'false': raise ValueError("Only all lowercase booleans allowed") elif v[0] == '"' or v[0] == "'": quotechar = v[0] testv = v[1:].split(quotechar) triplequote = False triplequotecount = 0 if len(testv) > 1 and testv[0] == '' and testv[1] == '': testv = testv[2:] triplequote = True closed = False for tv in testv: if tv == '': if triplequote: triplequotecount += 1 else: closed = True else: oddbackslash = False try: i = -1 j = tv[i] while j == '\\': oddbackslash = not oddbackslash i -= 1 j = tv[i] except IndexError: pass if not oddbackslash: if closed: raise ValueError("Found tokens after a closed " + "string. Invalid TOML.") else: if not triplequote or triplequotecount > 1: closed = True else: triplequotecount = 0 if quotechar == '"': escapeseqs = v.split('\\')[1:] backslash = False for i in escapeseqs: if i == '': backslash = not backslash else: if i[0] not in _escapes and (i[0] != 'u' and i[0] != 'U' and not backslash): raise ValueError("Reserved escape sequence used") if backslash: backslash = False for prefix in ["\\u", "\\U"]: if prefix in v: hexbytes = v.split(prefix) v = _load_unicode_escapes(hexbytes[0], hexbytes[1:], prefix) v = _unescape(v) if len(v) > 1 and v[1] == quotechar and (len(v) < 3 or v[1] == v[2]): v = v[2:-2] return (v[1:-1], "str") elif v[0] == '[': return (self.load_array(v), "array") elif v[0] == '{': inline_object = self.get_empty_inline_table() self.load_inline_object(v, inline_object) return (inline_object, "inline_object") elif TIME_RE.match(v): h, m, s, _, ms = TIME_RE.match(v).groups() time = datetime.time(int(h), int(m), int(s), int(ms) if ms else 0) return (time, "time") else: parsed_date = _load_date(v) if parsed_date is not None: return (parsed_date, "date") if not strictly_valid: raise ValueError("Weirdness with leading zeroes or " "underscores in your number.") itype = "int" neg = False if v[0] == '-': neg = True v = v[1:] elif v[0] == '+': v = v[1:] v = v.replace('_', '') lowerv = v.lower() if '.' in v or ('x' not in v and ('e' in v or 'E' in v)): if '.' in v and v.split('.', 1)[1] == '': raise ValueError("This float is missing digits after " "the point") if v[0] not in '0123456789': raise ValueError("This float doesn't have a leading " "digit") v = float(v) itype = "float" elif len(lowerv) == 3 and (lowerv == 'inf' or lowerv == 'nan'): v = float(v) itype = "float" if itype == "int": v = int(v, 0) if neg: return (0 - v, itype) return (v, itype) def bounded_string(self, s): if len(s) == 0: return True if s[-1] != s[0]: return False i = -2 backslash = False while len(s) + i > 0: if s[i] == "\\": backslash = not backslash i -= 1 else: break return not backslash def _load_array_isstrarray(self, a): a = a[1:-1].strip() if a != '' and (a[0] == '"' or a[0] == "'"): return True return False def load_array(self, a): atype = None retval = [] a = a.strip() if '[' not in a[1:-1] or "" != a[1:-1].split('[')[0].strip(): strarray = self._load_array_isstrarray(a) if not a[1:-1].strip().startswith('{'): a = a[1:-1].split(',') else: # a is an inline object, we must find the matching parenthesis # to define groups new_a = [] start_group_index = 1 end_group_index = 2 open_bracket_count = 1 if a[start_group_index] == '{' else 0 in_str = False while end_group_index < len(a[1:]): if a[end_group_index] == '"' or a[end_group_index] == "'": if in_str: backslash_index = end_group_index - 1 while (backslash_index > -1 and a[backslash_index] == '\\'): in_str = not in_str backslash_index -= 1 in_str = not in_str if not in_str and a[end_group_index] == '{': open_bracket_count += 1 if in_str or a[end_group_index] != '}': end_group_index += 1 continue elif a[end_group_index] == '}' and open_bracket_count > 1: open_bracket_count -= 1 end_group_index += 1 continue # Increase end_group_index by 1 to get the closing bracket end_group_index += 1 new_a.append(a[start_group_index:end_group_index]) # The next start index is at least after the closing # bracket, a closing bracket can be followed by a comma # since we are in an array. start_group_index = end_group_index + 1 while (start_group_index < len(a[1:]) and a[start_group_index] != '{'): start_group_index += 1 end_group_index = start_group_index + 1 a = new_a b = 0 if strarray: while b < len(a) - 1: ab = a[b].strip() while (not self.bounded_string(ab) or (len(ab) > 2 and ab[0] == ab[1] == ab[2] and ab[-2] != ab[0] and ab[-3] != ab[0])): a[b] = a[b] + ',' + a[b + 1] ab = a[b].strip() if b < len(a) - 2: a = a[:b + 1] + a[b + 2:] else: a = a[:b + 1] b += 1 else: al = list(a[1:-1]) a = [] openarr = 0 j = 0 for i in _range(len(al)): if al[i] == '[': openarr += 1 elif al[i] == ']': openarr -= 1 elif al[i] == ',' and not openarr: a.append(''.join(al[j:i])) j = i + 1 a.append(''.join(al[j:])) for i in _range(len(a)): a[i] = a[i].strip() if a[i] != '': nval, ntype = self.load_value(a[i]) if atype: if ntype != atype: raise ValueError("Not a homogeneous array") else: atype = ntype retval.append(nval) return retval def preserve_comment(self, line_no, key, comment, beginline): pass def embed_comments(self, idx, currentlevel): pass class TomlPreserveCommentDecoder(TomlDecoder): def __init__(self, _dict=dict): self.saved_comments = {} super(TomlPreserveCommentDecoder, self).__init__(_dict) def preserve_comment(self, line_no, key, comment, beginline): self.saved_comments[line_no] = (key, comment, beginline) def embed_comments(self, idx, currentlevel): if idx not in self.saved_comments: return key, comment, beginline = self.saved_comments[idx] currentlevel[key] = CommentValue(currentlevel[key], comment, beginline, self._dict)
zdppy-toml
/zdppy_toml-0.1.0.tar.gz/zdppy_toml-0.1.0/zdppy_toml/libs/toml/decoder.py
decoder.py
import os from typing import Union, Tuple, List, Dict from .libs import yaml class Yaml: def __init__(self, config: str = "config/config.yaml", config_secret: str = "config/secret/.config.yaml" ): """ yaml文件操作对象 :param config: 普通配置文件 :param config_secret: 私密的配置文件 """ self.__config_file = config self.__config_secret_file = config_secret self.config = {} # 配置对象 self.__init_config() # 初始化配置对象 def __init_config(self): """ 初始化配置 :return: """ # 读取公共配置 if os.path.exists(self.__config_file): with open(self.__config_file, "r") as f: config = yaml.safe_load(f) self.config.update(config) # 读取私密配置 if os.path.exists(self.__config_secret_file): with open(self.__config_secret_file, "r") as f: config = yaml.safe_load(f) self.config.update(config) def __read_config(self, config: str): """ 读取单个配置文件 :param config: 配置文件 :return: """ if os.path.exists(config): with open(config, "r") as f: c = yaml.safe_load(f) self.config.update(c) def read_config(self, config: Union[str, List, Tuple]): """ 读取配置 :param config:配置源 :return: """ if isinstance(config, str): self.__read_config(config) elif isinstance(config, list) or isinstance(config, tuple): for c in config: self.__read_config(c) def save_config(self, config="config/zdppy_yaml_config.yaml"): """ 保存配置 :param config:配置文件地址 :return: """ with open(config, "w") as f: yaml.dump(self.config, f) def update_config(self, config: Union[Dict, str, List, Tuple]): """ 更新配置 :param config:配置对象 :return: """ if isinstance(config, dict): self.config.update(config) else: self.read_config(config) def __str__(self): return str(self.config)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/zdppy_yaml.py
zdppy_yaml.py
__all__ = ['BaseResolver', 'Resolver'] from .error import * from .nodes import * import re class ResolverError(YAMLError): pass class BaseResolver: DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str' DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq' DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' yaml_implicit_resolvers = {} yaml_path_resolvers = {} def __init__(self): self.resolver_exact_paths = [] self.resolver_prefix_paths = [] @classmethod def add_implicit_resolver(cls, tag, regexp, first): if not 'yaml_implicit_resolvers' in cls.__dict__: implicit_resolvers = {} for key in cls.yaml_implicit_resolvers: implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:] cls.yaml_implicit_resolvers = implicit_resolvers if first is None: first = [None] for ch in first: cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp)) @classmethod def add_path_resolver(cls, tag, path, kind=None): # Note: `add_path_resolver` is experimental. The API could be changed. # `new_path` is a pattern that is matched against the path from the # root to the node that is being considered. `node_path` elements are # tuples `(node_check, index_check)`. `node_check` is a node class: # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None` # matches any kind of a node. `index_check` could be `None`, a boolean # value, a string value, or a number. `None` and `False` match against # any _value_ of sequence and mapping nodes. `True` matches against # any _key_ of a mapping node. A string `index_check` matches against # a mapping value that corresponds to a scalar key which content is # equal to the `index_check` value. An integer `index_check` matches # against a sequence value with the index equal to `index_check`. if not 'yaml_path_resolvers' in cls.__dict__: cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy() new_path = [] for element in path: if isinstance(element, (list, tuple)): if len(element) == 2: node_check, index_check = element elif len(element) == 1: node_check = element[0] index_check = True else: raise ResolverError("Invalid path element: %s" % element) else: node_check = None index_check = element if node_check is str: node_check = ScalarNode elif node_check is list: node_check = SequenceNode elif node_check is dict: node_check = MappingNode elif node_check not in [ScalarNode, SequenceNode, MappingNode] \ and not isinstance(node_check, str) \ and node_check is not None: raise ResolverError("Invalid node checker: %s" % node_check) if not isinstance(index_check, (str, int)) \ and index_check is not None: raise ResolverError("Invalid index checker: %s" % index_check) new_path.append((node_check, index_check)) if kind is str: kind = ScalarNode elif kind is list: kind = SequenceNode elif kind is dict: kind = MappingNode elif kind not in [ScalarNode, SequenceNode, MappingNode] \ and kind is not None: raise ResolverError("Invalid node kind: %s" % kind) cls.yaml_path_resolvers[tuple(new_path), kind] = tag def descend_resolver(self, current_node, current_index): if not self.yaml_path_resolvers: return exact_paths = {} prefix_paths = [] if current_node: depth = len(self.resolver_prefix_paths) for path, kind in self.resolver_prefix_paths[-1]: if self.check_resolver_prefix(depth, path, kind, current_node, current_index): if len(path) > depth: prefix_paths.append((path, kind)) else: exact_paths[kind] = self.yaml_path_resolvers[path, kind] else: for path, kind in self.yaml_path_resolvers: if not path: exact_paths[kind] = self.yaml_path_resolvers[path, kind] else: prefix_paths.append((path, kind)) self.resolver_exact_paths.append(exact_paths) self.resolver_prefix_paths.append(prefix_paths) def ascend_resolver(self): if not self.yaml_path_resolvers: return self.resolver_exact_paths.pop() self.resolver_prefix_paths.pop() def check_resolver_prefix(self, depth, path, kind, current_node, current_index): node_check, index_check = path[depth-1] if isinstance(node_check, str): if current_node.tag != node_check: return elif node_check is not None: if not isinstance(current_node, node_check): return if index_check is True and current_index is not None: return if (index_check is False or index_check is None) \ and current_index is None: return if isinstance(index_check, str): if not (isinstance(current_index, ScalarNode) and index_check == current_index.value): return elif isinstance(index_check, int) and not isinstance(index_check, bool): if index_check != current_index: return return True def resolve(self, kind, value, implicit): if kind is ScalarNode and implicit[0]: if value == '': resolvers = self.yaml_implicit_resolvers.get('', []) else: resolvers = self.yaml_implicit_resolvers.get(value[0], []) wildcard_resolvers = self.yaml_implicit_resolvers.get(None, []) for tag, regexp in resolvers + wildcard_resolvers: if regexp.match(value): return tag implicit = implicit[1] if self.yaml_path_resolvers: exact_paths = self.resolver_exact_paths[-1] if kind in exact_paths: return exact_paths[kind] if None in exact_paths: return exact_paths[None] if kind is ScalarNode: return self.DEFAULT_SCALAR_TAG elif kind is SequenceNode: return self.DEFAULT_SEQUENCE_TAG elif kind is MappingNode: return self.DEFAULT_MAPPING_TAG class Resolver(BaseResolver): pass Resolver.add_implicit_resolver( 'tag:yaml.org,2002:bool', re.compile(r'''^(?:yes|Yes|YES|no|No|NO |true|True|TRUE|false|False|FALSE |on|On|ON|off|Off|OFF)$''', re.X), list('yYnNtTfFoO')) Resolver.add_implicit_resolver( 'tag:yaml.org,2002:float', re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? |\.[0-9][0-9_]*(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]* |[-+]?\.(?:inf|Inf|INF) |\.(?:nan|NaN|NAN))$''', re.X), list('-+0123456789.')) Resolver.add_implicit_resolver( 'tag:yaml.org,2002:int', re.compile(r'''^(?:[-+]?0b[0-1_]+ |[-+]?0[0-7_]+ |[-+]?(?:0|[1-9][0-9_]*) |[-+]?0x[0-9a-fA-F_]+ |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), list('-+0123456789')) Resolver.add_implicit_resolver( 'tag:yaml.org,2002:merge', re.compile(r'^(?:<<)$'), ['<']) Resolver.add_implicit_resolver( 'tag:yaml.org,2002:null', re.compile(r'''^(?: ~ |null|Null|NULL | )$''', re.X), ['~', 'n', 'N', '']) Resolver.add_implicit_resolver( 'tag:yaml.org,2002:timestamp', re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? (?:[Tt]|[ \t]+)[0-9][0-9]? :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)? (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), list('0123456789')) Resolver.add_implicit_resolver( 'tag:yaml.org,2002:value', re.compile(r'^(?:=)$'), ['=']) # The following resolver is only for documentation purposes. It cannot work # because plain scalars cannot start with '!', '&', or '*'. Resolver.add_implicit_resolver( 'tag:yaml.org,2002:yaml', re.compile(r'^(?:!|&|\*)$'), list('!&*'))
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/resolver.py
resolver.py
__all__ = ['Emitter', 'EmitterError'] from .error import YAMLError from .events import * class EmitterError(YAMLError): pass class ScalarAnalysis: def __init__(self, scalar, empty, multiline, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block): self.scalar = scalar self.empty = empty self.multiline = multiline self.allow_flow_plain = allow_flow_plain self.allow_block_plain = allow_block_plain self.allow_single_quoted = allow_single_quoted self.allow_double_quoted = allow_double_quoted self.allow_block = allow_block class Emitter: DEFAULT_TAG_PREFIXES = { '!' : '!', 'tag:yaml.org,2002:' : '!!', } def __init__(self, stream, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None): # The stream should have the methods `write` and possibly `flush`. self.stream = stream # Encoding can be overridden by STREAM-START. self.encoding = None # Emitter is a state machine with a stack of states to handle nested # structures. self.states = [] self.state = self.expect_stream_start # Current event and the event queue. self.events = [] self.event = None # The current indentation level and the stack of previous indents. self.indents = [] self.indent = None # Flow level. self.flow_level = 0 # Contexts. self.root_context = False self.sequence_context = False self.mapping_context = False self.simple_key_context = False # Characteristics of the last emitted character: # - current position. # - is it a whitespace? # - is it an indention character # (indentation space, '-', '?', or ':')? self.line = 0 self.column = 0 self.whitespace = True self.indention = True # Whether the document requires an explicit document indicator self.open_ended = False # Formatting details. self.canonical = canonical self.allow_unicode = allow_unicode self.best_indent = 2 if indent and 1 < indent < 10: self.best_indent = indent self.best_width = 80 if width and width > self.best_indent*2: self.best_width = width self.best_line_break = '\n' if line_break in ['\r', '\n', '\r\n']: self.best_line_break = line_break # Tag prefixes. self.tag_prefixes = None # Prepared anchor and tag. self.prepared_anchor = None self.prepared_tag = None # Scalar analysis and style. self.analysis = None self.style = None def dispose(self): # Reset the state attributes (to clear self-references) self.states = [] self.state = None def emit(self, event): self.events.append(event) while not self.need_more_events(): self.event = self.events.pop(0) self.state() self.event = None # In some cases, we wait for a few next events before emitting. def need_more_events(self): if not self.events: return True event = self.events[0] if isinstance(event, DocumentStartEvent): return self.need_events(1) elif isinstance(event, SequenceStartEvent): return self.need_events(2) elif isinstance(event, MappingStartEvent): return self.need_events(3) else: return False def need_events(self, count): level = 0 for event in self.events[1:]: if isinstance(event, (DocumentStartEvent, CollectionStartEvent)): level += 1 elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)): level -= 1 elif isinstance(event, StreamEndEvent): level = -1 if level < 0: return False return (len(self.events) < count+1) def increase_indent(self, flow=False, indentless=False): self.indents.append(self.indent) if self.indent is None: if flow: self.indent = self.best_indent else: self.indent = 0 elif not indentless: self.indent += self.best_indent # States. # Stream handlers. def expect_stream_start(self): if isinstance(self.event, StreamStartEvent): if self.event.encoding and not hasattr(self.stream, 'encoding'): self.encoding = self.event.encoding self.write_stream_start() self.state = self.expect_first_document_start else: raise EmitterError("expected StreamStartEvent, but got %s" % self.event) def expect_nothing(self): raise EmitterError("expected nothing, but got %s" % self.event) # Document handlers. def expect_first_document_start(self): return self.expect_document_start(first=True) def expect_document_start(self, first=False): if isinstance(self.event, DocumentStartEvent): if (self.event.version or self.event.tags) and self.open_ended: self.write_indicator('...', True) self.write_indent() if self.event.version: version_text = self.prepare_version(self.event.version) self.write_version_directive(version_text) self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy() if self.event.tags: handles = sorted(self.event.tags.keys()) for handle in handles: prefix = self.event.tags[handle] self.tag_prefixes[prefix] = handle handle_text = self.prepare_tag_handle(handle) prefix_text = self.prepare_tag_prefix(prefix) self.write_tag_directive(handle_text, prefix_text) implicit = (first and not self.event.explicit and not self.canonical and not self.event.version and not self.event.tags and not self.check_empty_document()) if not implicit: self.write_indent() self.write_indicator('---', True) if self.canonical: self.write_indent() self.state = self.expect_document_root elif isinstance(self.event, StreamEndEvent): if self.open_ended: self.write_indicator('...', True) self.write_indent() self.write_stream_end() self.state = self.expect_nothing else: raise EmitterError("expected DocumentStartEvent, but got %s" % self.event) def expect_document_end(self): if isinstance(self.event, DocumentEndEvent): self.write_indent() if self.event.explicit: self.write_indicator('...', True) self.write_indent() self.flush_stream() self.state = self.expect_document_start else: raise EmitterError("expected DocumentEndEvent, but got %s" % self.event) def expect_document_root(self): self.states.append(self.expect_document_end) self.expect_node(root=True) # Node handlers. def expect_node(self, root=False, sequence=False, mapping=False, simple_key=False): self.root_context = root self.sequence_context = sequence self.mapping_context = mapping self.simple_key_context = simple_key if isinstance(self.event, AliasEvent): self.expect_alias() elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): self.process_anchor('&') self.process_tag() if isinstance(self.event, ScalarEvent): self.expect_scalar() elif isinstance(self.event, SequenceStartEvent): if self.flow_level or self.canonical or self.event.flow_style \ or self.check_empty_sequence(): self.expect_flow_sequence() else: self.expect_block_sequence() elif isinstance(self.event, MappingStartEvent): if self.flow_level or self.canonical or self.event.flow_style \ or self.check_empty_mapping(): self.expect_flow_mapping() else: self.expect_block_mapping() else: raise EmitterError("expected NodeEvent, but got %s" % self.event) def expect_alias(self): if self.event.anchor is None: raise EmitterError("anchor is not specified for alias") self.process_anchor('*') self.state = self.states.pop() def expect_scalar(self): self.increase_indent(flow=True) self.process_scalar() self.indent = self.indents.pop() self.state = self.states.pop() # Flow sequence handlers. def expect_flow_sequence(self): self.write_indicator('[', True, whitespace=True) self.flow_level += 1 self.increase_indent(flow=True) self.state = self.expect_first_flow_sequence_item def expect_first_flow_sequence_item(self): if isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 self.write_indicator(']', False) self.state = self.states.pop() else: if self.canonical or self.column > self.best_width: self.write_indent() self.states.append(self.expect_flow_sequence_item) self.expect_node(sequence=True) def expect_flow_sequence_item(self): if isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 if self.canonical: self.write_indicator(',', False) self.write_indent() self.write_indicator(']', False) self.state = self.states.pop() else: self.write_indicator(',', False) if self.canonical or self.column > self.best_width: self.write_indent() self.states.append(self.expect_flow_sequence_item) self.expect_node(sequence=True) # Flow mapping handlers. def expect_flow_mapping(self): self.write_indicator('{', True, whitespace=True) self.flow_level += 1 self.increase_indent(flow=True) self.state = self.expect_first_flow_mapping_key def expect_first_flow_mapping_key(self): if isinstance(self.event, MappingEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 self.write_indicator('}', False) self.state = self.states.pop() else: if self.canonical or self.column > self.best_width: self.write_indent() if not self.canonical and self.check_simple_key(): self.states.append(self.expect_flow_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: self.write_indicator('?', True) self.states.append(self.expect_flow_mapping_value) self.expect_node(mapping=True) def expect_flow_mapping_key(self): if isinstance(self.event, MappingEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 if self.canonical: self.write_indicator(',', False) self.write_indent() self.write_indicator('}', False) self.state = self.states.pop() else: self.write_indicator(',', False) if self.canonical or self.column > self.best_width: self.write_indent() if not self.canonical and self.check_simple_key(): self.states.append(self.expect_flow_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: self.write_indicator('?', True) self.states.append(self.expect_flow_mapping_value) self.expect_node(mapping=True) def expect_flow_mapping_simple_value(self): self.write_indicator(':', False) self.states.append(self.expect_flow_mapping_key) self.expect_node(mapping=True) def expect_flow_mapping_value(self): if self.canonical or self.column > self.best_width: self.write_indent() self.write_indicator(':', True) self.states.append(self.expect_flow_mapping_key) self.expect_node(mapping=True) # Block sequence handlers. def expect_block_sequence(self): indentless = (self.mapping_context and not self.indention) self.increase_indent(flow=False, indentless=indentless) self.state = self.expect_first_block_sequence_item def expect_first_block_sequence_item(self): return self.expect_block_sequence_item(first=True) def expect_block_sequence_item(self, first=False): if not first and isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() self.state = self.states.pop() else: self.write_indent() self.write_indicator('-', True, indention=True) self.states.append(self.expect_block_sequence_item) self.expect_node(sequence=True) # Block mapping handlers. def expect_block_mapping(self): self.increase_indent(flow=False) self.state = self.expect_first_block_mapping_key def expect_first_block_mapping_key(self): return self.expect_block_mapping_key(first=True) def expect_block_mapping_key(self, first=False): if not first and isinstance(self.event, MappingEndEvent): self.indent = self.indents.pop() self.state = self.states.pop() else: self.write_indent() if self.check_simple_key(): self.states.append(self.expect_block_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: self.write_indicator('?', True, indention=True) self.states.append(self.expect_block_mapping_value) self.expect_node(mapping=True) def expect_block_mapping_simple_value(self): self.write_indicator(':', False) self.states.append(self.expect_block_mapping_key) self.expect_node(mapping=True) def expect_block_mapping_value(self): self.write_indent() self.write_indicator(':', True, indention=True) self.states.append(self.expect_block_mapping_key) self.expect_node(mapping=True) # Checkers. def check_empty_sequence(self): return (isinstance(self.event, SequenceStartEvent) and self.events and isinstance(self.events[0], SequenceEndEvent)) def check_empty_mapping(self): return (isinstance(self.event, MappingStartEvent) and self.events and isinstance(self.events[0], MappingEndEvent)) def check_empty_document(self): if not isinstance(self.event, DocumentStartEvent) or not self.events: return False event = self.events[0] return (isinstance(event, ScalarEvent) and event.anchor is None and event.tag is None and event.implicit and event.value == '') def check_simple_key(self): length = 0 if isinstance(self.event, NodeEvent) and self.event.anchor is not None: if self.prepared_anchor is None: self.prepared_anchor = self.prepare_anchor(self.event.anchor) length += len(self.prepared_anchor) if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \ and self.event.tag is not None: if self.prepared_tag is None: self.prepared_tag = self.prepare_tag(self.event.tag) length += len(self.prepared_tag) if isinstance(self.event, ScalarEvent): if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) length += len(self.analysis.scalar) return (length < 128 and (isinstance(self.event, AliasEvent) or (isinstance(self.event, ScalarEvent) and not self.analysis.empty and not self.analysis.multiline) or self.check_empty_sequence() or self.check_empty_mapping())) # Anchor, Tag, and Scalar processors. def process_anchor(self, indicator): if self.event.anchor is None: self.prepared_anchor = None return if self.prepared_anchor is None: self.prepared_anchor = self.prepare_anchor(self.event.anchor) if self.prepared_anchor: self.write_indicator(indicator+self.prepared_anchor, True) self.prepared_anchor = None def process_tag(self): tag = self.event.tag if isinstance(self.event, ScalarEvent): if self.style is None: self.style = self.choose_scalar_style() if ((not self.canonical or tag is None) and ((self.style == '' and self.event.implicit[0]) or (self.style != '' and self.event.implicit[1]))): self.prepared_tag = None return if self.event.implicit[0] and tag is None: tag = '!' self.prepared_tag = None else: if (not self.canonical or tag is None) and self.event.implicit: self.prepared_tag = None return if tag is None: raise EmitterError("tag is not specified") if self.prepared_tag is None: self.prepared_tag = self.prepare_tag(tag) if self.prepared_tag: self.write_indicator(self.prepared_tag, True) self.prepared_tag = None def choose_scalar_style(self): if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) if self.event.style == '"' or self.canonical: return '"' if not self.event.style and self.event.implicit[0]: if (not (self.simple_key_context and (self.analysis.empty or self.analysis.multiline)) and (self.flow_level and self.analysis.allow_flow_plain or (not self.flow_level and self.analysis.allow_block_plain))): return '' if self.event.style and self.event.style in '|>': if (not self.flow_level and not self.simple_key_context and self.analysis.allow_block): return self.event.style if not self.event.style or self.event.style == '\'': if (self.analysis.allow_single_quoted and not (self.simple_key_context and self.analysis.multiline)): return '\'' return '"' def process_scalar(self): if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) if self.style is None: self.style = self.choose_scalar_style() split = (not self.simple_key_context) #if self.analysis.multiline and split \ # and (not self.style or self.style in '\'\"'): # self.write_indent() if self.style == '"': self.write_double_quoted(self.analysis.scalar, split) elif self.style == '\'': self.write_single_quoted(self.analysis.scalar, split) elif self.style == '>': self.write_folded(self.analysis.scalar) elif self.style == '|': self.write_literal(self.analysis.scalar) else: self.write_plain(self.analysis.scalar, split) self.analysis = None self.style = None # Analyzers. def prepare_version(self, version): major, minor = version if major != 1: raise EmitterError("unsupported YAML version: %d.%d" % (major, minor)) return '%d.%d' % (major, minor) def prepare_tag_handle(self, handle): if not handle: raise EmitterError("tag handle must not be empty") if handle[0] != '!' or handle[-1] != '!': raise EmitterError("tag handle must start and end with '!': %r" % handle) for ch in handle[1:-1]: if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-_'): raise EmitterError("invalid character %r in the tag handle: %r" % (ch, handle)) return handle def prepare_tag_prefix(self, prefix): if not prefix: raise EmitterError("tag prefix must not be empty") chunks = [] start = end = 0 if prefix[0] == '!': end = 1 while end < len(prefix): ch = prefix[end] if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-;/?!:@&=+$,_.~*\'()[]': end += 1 else: if start < end: chunks.append(prefix[start:end]) start = end = end+1 data = ch.encode('utf-8') for ch in data: chunks.append('%%%02X' % ord(ch)) if start < end: chunks.append(prefix[start:end]) return ''.join(chunks) def prepare_tag(self, tag): if not tag: raise EmitterError("tag must not be empty") if tag == '!': return tag handle = None suffix = tag prefixes = sorted(self.tag_prefixes.keys()) for prefix in prefixes: if tag.startswith(prefix) \ and (prefix == '!' or len(prefix) < len(tag)): handle = self.tag_prefixes[prefix] suffix = tag[len(prefix):] chunks = [] start = end = 0 while end < len(suffix): ch = suffix[end] if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-;/?:@&=+$,_.~*\'()[]' \ or (ch == '!' and handle != '!'): end += 1 else: if start < end: chunks.append(suffix[start:end]) start = end = end+1 data = ch.encode('utf-8') for ch in data: chunks.append('%%%02X' % ch) if start < end: chunks.append(suffix[start:end]) suffix_text = ''.join(chunks) if handle: return '%s%s' % (handle, suffix_text) else: return '!<%s>' % suffix_text def prepare_anchor(self, anchor): if not anchor: raise EmitterError("anchor must not be empty") for ch in anchor: if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-_'): raise EmitterError("invalid character %r in the anchor: %r" % (ch, anchor)) return anchor def analyze_scalar(self, scalar): # Empty scalar is a special case. if not scalar: return ScalarAnalysis(scalar=scalar, empty=True, multiline=False, allow_flow_plain=False, allow_block_plain=True, allow_single_quoted=True, allow_double_quoted=True, allow_block=False) # Indicators and special characters. block_indicators = False flow_indicators = False line_breaks = False special_characters = False # Important whitespace combinations. leading_space = False leading_break = False trailing_space = False trailing_break = False break_space = False space_break = False # Check document indicators. if scalar.startswith('---') or scalar.startswith('...'): block_indicators = True flow_indicators = True # First character or preceded by a whitespace. preceded_by_whitespace = True # Last character or followed by a whitespace. followed_by_whitespace = (len(scalar) == 1 or scalar[1] in '\0 \t\r\n\x85\u2028\u2029') # The previous character is a space. previous_space = False # The previous character is a break. previous_break = False index = 0 while index < len(scalar): ch = scalar[index] # Check for indicators. if index == 0: # Leading indicators are special characters. if ch in '#,[]{}&*!|>\'\"%@`': flow_indicators = True block_indicators = True if ch in '?:': flow_indicators = True if followed_by_whitespace: block_indicators = True if ch == '-' and followed_by_whitespace: flow_indicators = True block_indicators = True else: # Some indicators cannot appear within a scalar as well. if ch in ',?[]{}': flow_indicators = True if ch == ':': flow_indicators = True if followed_by_whitespace: block_indicators = True if ch == '#' and preceded_by_whitespace: flow_indicators = True block_indicators = True # Check for line breaks, special, and unicode characters. if ch in '\n\x85\u2028\u2029': line_breaks = True if not (ch == '\n' or '\x20' <= ch <= '\x7E'): if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF' or '\uE000' <= ch <= '\uFFFD' or '\U00010000' <= ch < '\U0010ffff') and ch != '\uFEFF': unicode_characters = True if not self.allow_unicode: special_characters = True else: special_characters = True # Detect important whitespace combinations. if ch == ' ': if index == 0: leading_space = True if index == len(scalar)-1: trailing_space = True if previous_break: break_space = True previous_space = True previous_break = False elif ch in '\n\x85\u2028\u2029': if index == 0: leading_break = True if index == len(scalar)-1: trailing_break = True if previous_space: space_break = True previous_space = False previous_break = True else: previous_space = False previous_break = False # Prepare for the next character. index += 1 preceded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029') followed_by_whitespace = (index+1 >= len(scalar) or scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029') # Let's decide what styles are allowed. allow_flow_plain = True allow_block_plain = True allow_single_quoted = True allow_double_quoted = True allow_block = True # Leading and trailing whitespaces are bad for plain scalars. if (leading_space or leading_break or trailing_space or trailing_break): allow_flow_plain = allow_block_plain = False # We do not permit trailing spaces for block scalars. if trailing_space: allow_block = False # Spaces at the beginning of a new line are only acceptable for block # scalars. if break_space: allow_flow_plain = allow_block_plain = allow_single_quoted = False # Spaces followed by breaks, as well as special character are only # allowed for double quoted scalars. if space_break or special_characters: allow_flow_plain = allow_block_plain = \ allow_single_quoted = allow_block = False # Although the plain scalar writer supports breaks, we never emit # multiline plain scalars. if line_breaks: allow_flow_plain = allow_block_plain = False # Flow indicators are forbidden for flow plain scalars. if flow_indicators: allow_flow_plain = False # Block indicators are forbidden for block plain scalars. if block_indicators: allow_block_plain = False return ScalarAnalysis(scalar=scalar, empty=False, multiline=line_breaks, allow_flow_plain=allow_flow_plain, allow_block_plain=allow_block_plain, allow_single_quoted=allow_single_quoted, allow_double_quoted=allow_double_quoted, allow_block=allow_block) # Writers. def flush_stream(self): if hasattr(self.stream, 'flush'): self.stream.flush() def write_stream_start(self): # Write BOM if needed. if self.encoding and self.encoding.startswith('utf-16'): self.stream.write('\uFEFF'.encode(self.encoding)) def write_stream_end(self): self.flush_stream() def write_indicator(self, indicator, need_whitespace, whitespace=False, indention=False): if self.whitespace or not need_whitespace: data = indicator else: data = ' '+indicator self.whitespace = whitespace self.indention = self.indention and indention self.column += len(data) self.open_ended = False if self.encoding: data = data.encode(self.encoding) self.stream.write(data) def write_indent(self): indent = self.indent or 0 if not self.indention or self.column > indent \ or (self.column == indent and not self.whitespace): self.write_line_break() if self.column < indent: self.whitespace = True data = ' '*(indent-self.column) self.column = indent if self.encoding: data = data.encode(self.encoding) self.stream.write(data) def write_line_break(self, data=None): if data is None: data = self.best_line_break self.whitespace = True self.indention = True self.line += 1 self.column = 0 if self.encoding: data = data.encode(self.encoding) self.stream.write(data) def write_version_directive(self, version_text): data = '%%YAML %s' % version_text if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_line_break() def write_tag_directive(self, handle_text, prefix_text): data = '%%TAG %s %s' % (handle_text, prefix_text) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_line_break() # Scalar streams. def write_single_quoted(self, text, split=True): self.write_indicator('\'', True) spaces = False breaks = False start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if spaces: if ch is None or ch != ' ': if start+1 == end and self.column > self.best_width and split \ and start != 0 and end != len(text): self.write_indent() else: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end elif breaks: if ch is None or ch not in '\n\x85\u2028\u2029': if text[start] == '\n': self.write_line_break() for br in text[start:end]: if br == '\n': self.write_line_break() else: self.write_line_break(br) self.write_indent() start = end else: if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'': if start < end: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end if ch == '\'': data = '\'\'' self.column += 2 if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end + 1 if ch is not None: spaces = (ch == ' ') breaks = (ch in '\n\x85\u2028\u2029') end += 1 self.write_indicator('\'', False) ESCAPE_REPLACEMENTS = { '\0': '0', '\x07': 'a', '\x08': 'b', '\x09': 't', '\x0A': 'n', '\x0B': 'v', '\x0C': 'f', '\x0D': 'r', '\x1B': 'e', '\"': '\"', '\\': '\\', '\x85': 'N', '\xA0': '_', '\u2028': 'L', '\u2029': 'P', } def write_double_quoted(self, text, split=True): self.write_indicator('"', True) start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \ or not ('\x20' <= ch <= '\x7E' or (self.allow_unicode and ('\xA0' <= ch <= '\uD7FF' or '\uE000' <= ch <= '\uFFFD'))): if start < end: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end if ch is not None: if ch in self.ESCAPE_REPLACEMENTS: data = '\\'+self.ESCAPE_REPLACEMENTS[ch] elif ch <= '\xFF': data = '\\x%02X' % ord(ch) elif ch <= '\uFFFF': data = '\\u%04X' % ord(ch) else: data = '\\U%08X' % ord(ch) self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end+1 if 0 < end < len(text)-1 and (ch == ' ' or start >= end) \ and self.column+(end-start) > self.best_width and split: data = text[start:end]+'\\' if start < end: start = end self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_indent() self.whitespace = False self.indention = False if text[start] == ' ': data = '\\' self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) end += 1 self.write_indicator('"', False) def determine_block_hints(self, text): hints = '' if text: if text[0] in ' \n\x85\u2028\u2029': hints += str(self.best_indent) if text[-1] not in '\n\x85\u2028\u2029': hints += '-' elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029': hints += '+' return hints def write_folded(self, text): hints = self.determine_block_hints(text) self.write_indicator('>'+hints, True) if hints[-1:] == '+': self.open_ended = True self.write_line_break() leading_space = True spaces = False breaks = True start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if breaks: if ch is None or ch not in '\n\x85\u2028\u2029': if not leading_space and ch is not None and ch != ' ' \ and text[start] == '\n': self.write_line_break() leading_space = (ch == ' ') for br in text[start:end]: if br == '\n': self.write_line_break() else: self.write_line_break(br) if ch is not None: self.write_indent() start = end elif spaces: if ch != ' ': if start+1 == end and self.column > self.best_width: self.write_indent() else: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end else: if ch is None or ch in ' \n\x85\u2028\u2029': data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) if ch is None: self.write_line_break() start = end if ch is not None: breaks = (ch in '\n\x85\u2028\u2029') spaces = (ch == ' ') end += 1 def write_literal(self, text): hints = self.determine_block_hints(text) self.write_indicator('|'+hints, True) if hints[-1:] == '+': self.open_ended = True self.write_line_break() breaks = True start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if breaks: if ch is None or ch not in '\n\x85\u2028\u2029': for br in text[start:end]: if br == '\n': self.write_line_break() else: self.write_line_break(br) if ch is not None: self.write_indent() start = end else: if ch is None or ch in '\n\x85\u2028\u2029': data = text[start:end] if self.encoding: data = data.encode(self.encoding) self.stream.write(data) if ch is None: self.write_line_break() start = end if ch is not None: breaks = (ch in '\n\x85\u2028\u2029') end += 1 def write_plain(self, text, split=True): if self.root_context: self.open_ended = True if not text: return if not self.whitespace: data = ' ' self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.whitespace = False self.indention = False spaces = False breaks = False start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if spaces: if ch != ' ': if start+1 == end and self.column > self.best_width and split: self.write_indent() self.whitespace = False self.indention = False else: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end elif breaks: if ch not in '\n\x85\u2028\u2029': if text[start] == '\n': self.write_line_break() for br in text[start:end]: if br == '\n': self.write_line_break() else: self.write_line_break(br) self.write_indent() self.whitespace = False self.indention = False start = end else: if ch is None or ch in ' \n\x85\u2028\u2029': data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end if ch is not None: spaces = (ch == ' ') breaks = (ch in '\n\x85\u2028\u2029') end += 1
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/emitter.py
emitter.py
__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer', 'RepresenterError'] from .error import * from .nodes import * import datetime, copyreg, types, base64, collections class RepresenterError(YAMLError): pass class BaseRepresenter: yaml_representers = {} yaml_multi_representers = {} def __init__(self, default_style=None, default_flow_style=False, sort_keys=True): self.default_style = default_style self.sort_keys = sort_keys self.default_flow_style = default_flow_style self.represented_objects = {} self.object_keeper = [] self.alias_key = None def represent(self, data): node = self.represent_data(data) self.serialize(node) self.represented_objects = {} self.object_keeper = [] self.alias_key = None def represent_data(self, data): if self.ignore_aliases(data): self.alias_key = None else: self.alias_key = id(data) if self.alias_key is not None: if self.alias_key in self.represented_objects: node = self.represented_objects[self.alias_key] #if node is None: # raise RepresenterError("recursive objects are not allowed: %r" % data) return node #self.represented_objects[alias_key] = None self.object_keeper.append(data) data_types = type(data).__mro__ if data_types[0] in self.yaml_representers: node = self.yaml_representers[data_types[0]](self, data) else: for data_type in data_types: if data_type in self.yaml_multi_representers: node = self.yaml_multi_representers[data_type](self, data) break else: if None in self.yaml_multi_representers: node = self.yaml_multi_representers[None](self, data) elif None in self.yaml_representers: node = self.yaml_representers[None](self, data) else: node = ScalarNode(None, str(data)) #if alias_key is not None: # self.represented_objects[alias_key] = node return node @classmethod def add_representer(cls, data_type, representer): if not 'yaml_representers' in cls.__dict__: cls.yaml_representers = cls.yaml_representers.copy() cls.yaml_representers[data_type] = representer @classmethod def add_multi_representer(cls, data_type, representer): if not 'yaml_multi_representers' in cls.__dict__: cls.yaml_multi_representers = cls.yaml_multi_representers.copy() cls.yaml_multi_representers[data_type] = representer def represent_scalar(self, tag, value, style=None): if style is None: style = self.default_style node = ScalarNode(tag, value, style=style) if self.alias_key is not None: self.represented_objects[self.alias_key] = node return node def represent_sequence(self, tag, sequence, flow_style=None): value = [] node = SequenceNode(tag, value, flow_style=flow_style) if self.alias_key is not None: self.represented_objects[self.alias_key] = node best_style = True for item in sequence: node_item = self.represent_data(item) if not (isinstance(node_item, ScalarNode) and not node_item.style): best_style = False value.append(node_item) if flow_style is None: if self.default_flow_style is not None: node.flow_style = self.default_flow_style else: node.flow_style = best_style return node def represent_mapping(self, tag, mapping, flow_style=None): value = [] node = MappingNode(tag, value, flow_style=flow_style) if self.alias_key is not None: self.represented_objects[self.alias_key] = node best_style = True if hasattr(mapping, 'items'): mapping = list(mapping.items()) if self.sort_keys: try: mapping = sorted(mapping) except TypeError: pass for item_key, item_value in mapping: node_key = self.represent_data(item_key) node_value = self.represent_data(item_value) if not (isinstance(node_key, ScalarNode) and not node_key.style): best_style = False if not (isinstance(node_value, ScalarNode) and not node_value.style): best_style = False value.append((node_key, node_value)) if flow_style is None: if self.default_flow_style is not None: node.flow_style = self.default_flow_style else: node.flow_style = best_style return node def ignore_aliases(self, data): return False class SafeRepresenter(BaseRepresenter): def ignore_aliases(self, data): if data is None: return True if isinstance(data, tuple) and data == (): return True if isinstance(data, (str, bytes, bool, int, float)): return True def represent_none(self, data): return self.represent_scalar('tag:yaml.org,2002:null', 'null') def represent_str(self, data): return self.represent_scalar('tag:yaml.org,2002:str', data) def represent_binary(self, data): if hasattr(base64, 'encodebytes'): data = base64.encodebytes(data).decode('ascii') else: data = base64.encodestring(data).decode('ascii') return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|') def represent_bool(self, data): if data: value = 'true' else: value = 'false' return self.represent_scalar('tag:yaml.org,2002:bool', value) def represent_int(self, data): return self.represent_scalar('tag:yaml.org,2002:int', str(data)) inf_value = 1e300 while repr(inf_value) != repr(inf_value*inf_value): inf_value *= inf_value def represent_float(self, data): if data != data or (data == 0.0 and data == 1.0): value = '.nan' elif data == self.inf_value: value = '.inf' elif data == -self.inf_value: value = '-.inf' else: value = repr(data).lower() # Note that in some cases `repr(data)` represents a float number # without the decimal parts. For instance: # >>> repr(1e17) # '1e17' # Unfortunately, this is not a valid float representation according # to the definition of the `!!float` tag. We fix this by adding # '.0' before the 'e' symbol. if '.' not in value and 'e' in value: value = value.replace('e', '.0e', 1) return self.represent_scalar('tag:yaml.org,2002:float', value) def represent_list(self, data): #pairs = (len(data) > 0 and isinstance(data, list)) #if pairs: # for item in data: # if not isinstance(item, tuple) or len(item) != 2: # pairs = False # break #if not pairs: return self.represent_sequence('tag:yaml.org,2002:seq', data) #value = [] #for item_key, item_value in data: # value.append(self.represent_mapping(u'tag:yaml.org,2002:map', # [(item_key, item_value)])) #return SequenceNode(u'tag:yaml.org,2002:pairs', value) def represent_dict(self, data): return self.represent_mapping('tag:yaml.org,2002:map', data) def represent_set(self, data): value = {} for key in data: value[key] = None return self.represent_mapping('tag:yaml.org,2002:set', value) def represent_date(self, data): value = data.isoformat() return self.represent_scalar('tag:yaml.org,2002:timestamp', value) def represent_datetime(self, data): value = data.isoformat(' ') return self.represent_scalar('tag:yaml.org,2002:timestamp', value) def represent_yaml_object(self, tag, data, cls, flow_style=None): if hasattr(data, '__getstate__'): state = data.__getstate__() else: state = data.__dict__.copy() return self.represent_mapping(tag, state, flow_style=flow_style) def represent_undefined(self, data): raise RepresenterError("cannot represent an object", data) SafeRepresenter.add_representer(type(None), SafeRepresenter.represent_none) SafeRepresenter.add_representer(str, SafeRepresenter.represent_str) SafeRepresenter.add_representer(bytes, SafeRepresenter.represent_binary) SafeRepresenter.add_representer(bool, SafeRepresenter.represent_bool) SafeRepresenter.add_representer(int, SafeRepresenter.represent_int) SafeRepresenter.add_representer(float, SafeRepresenter.represent_float) SafeRepresenter.add_representer(list, SafeRepresenter.represent_list) SafeRepresenter.add_representer(tuple, SafeRepresenter.represent_list) SafeRepresenter.add_representer(dict, SafeRepresenter.represent_dict) SafeRepresenter.add_representer(set, SafeRepresenter.represent_set) SafeRepresenter.add_representer(datetime.date, SafeRepresenter.represent_date) SafeRepresenter.add_representer(datetime.datetime, SafeRepresenter.represent_datetime) SafeRepresenter.add_representer(None, SafeRepresenter.represent_undefined) class Representer(SafeRepresenter): def represent_complex(self, data): if data.imag == 0.0: data = '%r' % data.real elif data.real == 0.0: data = '%rj' % data.imag elif data.imag > 0: data = '%r+%rj' % (data.real, data.imag) else: data = '%r%rj' % (data.real, data.imag) return self.represent_scalar('tag:yaml.org,2002:python/complex', data) def represent_tuple(self, data): return self.represent_sequence('tag:yaml.org,2002:python/tuple', data) def represent_name(self, data): name = '%s.%s' % (data.__module__, data.__name__) return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '') def represent_module(self, data): return self.represent_scalar( 'tag:yaml.org,2002:python/module:'+data.__name__, '') def represent_object(self, data): # We use __reduce__ API to save the data. data.__reduce__ returns # a tuple of length 2-5: # (function, args, state, listitems, dictitems) # For reconstructing, we calls function(*args), then set its state, # listitems, and dictitems if they are not None. # A special case is when function.__name__ == '__newobj__'. In this # case we create the object with args[0].__new__(*args). # Another special case is when __reduce__ returns a string - we don't # support it. # We produce a !!python/object, !!python/object/new or # !!python/object/apply node. cls = type(data) if cls in copyreg.dispatch_table: reduce = copyreg.dispatch_table[cls](data) elif hasattr(data, '__reduce_ex__'): reduce = data.__reduce_ex__(2) elif hasattr(data, '__reduce__'): reduce = data.__reduce__() else: raise RepresenterError("cannot represent an object", data) reduce = (list(reduce)+[None]*5)[:5] function, args, state, listitems, dictitems = reduce args = list(args) if state is None: state = {} if listitems is not None: listitems = list(listitems) if dictitems is not None: dictitems = dict(dictitems) if function.__name__ == '__newobj__': function = args[0] args = args[1:] tag = 'tag:yaml.org,2002:python/object/new:' newobj = True else: tag = 'tag:yaml.org,2002:python/object/apply:' newobj = False function_name = '%s.%s' % (function.__module__, function.__name__) if not args and not listitems and not dictitems \ and isinstance(state, dict) and newobj: return self.represent_mapping( 'tag:yaml.org,2002:python/object:'+function_name, state) if not listitems and not dictitems \ and isinstance(state, dict) and not state: return self.represent_sequence(tag+function_name, args) value = {} if args: value['args'] = args if state or not isinstance(state, dict): value['state'] = state if listitems: value['listitems'] = listitems if dictitems: value['dictitems'] = dictitems return self.represent_mapping(tag+function_name, value) def represent_ordered_dict(self, data): # Provide uniform representation across different Python versions. data_type = type(data) tag = 'tag:yaml.org,2002:python/object/apply:%s.%s' \ % (data_type.__module__, data_type.__name__) items = [[key, value] for key, value in data.items()] return self.represent_sequence(tag, [items]) Representer.add_representer(complex, Representer.represent_complex) Representer.add_representer(tuple, Representer.represent_tuple) Representer.add_multi_representer(type, Representer.represent_name) Representer.add_representer(collections.OrderedDict, Representer.represent_ordered_dict) Representer.add_representer(types.FunctionType, Representer.represent_name) Representer.add_representer(types.BuiltinFunctionType, Representer.represent_name) Representer.add_representer(types.ModuleType, Representer.represent_module) Representer.add_multi_representer(object, Representer.represent_object)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/representer.py
representer.py
__all__ = [ 'CBaseLoader', 'CSafeLoader', 'CFullLoader', 'CUnsafeLoader', 'CLoader', 'CBaseDumper', 'CSafeDumper', 'CDumper' ] from yaml._yaml import CParser, CEmitter from .constructor import * from .serializer import * from .representer import * from .resolver import * class CBaseLoader(CParser, BaseConstructor, BaseResolver): def __init__(self, stream): CParser.__init__(self, stream) BaseConstructor.__init__(self) BaseResolver.__init__(self) class CSafeLoader(CParser, SafeConstructor, Resolver): def __init__(self, stream): CParser.__init__(self, stream) SafeConstructor.__init__(self) Resolver.__init__(self) class CFullLoader(CParser, FullConstructor, Resolver): def __init__(self, stream): CParser.__init__(self, stream) FullConstructor.__init__(self) Resolver.__init__(self) class CUnsafeLoader(CParser, UnsafeConstructor, Resolver): def __init__(self, stream): CParser.__init__(self, stream) UnsafeConstructor.__init__(self) Resolver.__init__(self) class CLoader(CParser, Constructor, Resolver): def __init__(self, stream): CParser.__init__(self, stream) Constructor.__init__(self) Resolver.__init__(self) class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): def __init__(self, stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True): CEmitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, encoding=encoding, allow_unicode=allow_unicode, line_break=line_break, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) Representer.__init__(self, default_style=default_style, default_flow_style=default_flow_style, sort_keys=sort_keys) Resolver.__init__(self) class CSafeDumper(CEmitter, SafeRepresenter, Resolver): def __init__(self, stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True): CEmitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, encoding=encoding, allow_unicode=allow_unicode, line_break=line_break, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) SafeRepresenter.__init__(self, default_style=default_style, default_flow_style=default_flow_style, sort_keys=sort_keys) Resolver.__init__(self) class CDumper(CEmitter, Serializer, Representer, Resolver): def __init__(self, stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True): CEmitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, encoding=encoding, allow_unicode=allow_unicode, line_break=line_break, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) Representer.__init__(self, default_style=default_style, default_flow_style=default_flow_style, sort_keys=sort_keys) Resolver.__init__(self)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/cyaml.py
cyaml.py
__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] class Mark: def __init__(self, name, index, line, column, buffer, pointer): self.name = name self.index = index self.line = line self.column = column self.buffer = buffer self.pointer = pointer def get_snippet(self, indent=4, max_length=75): if self.buffer is None: return None head = '' start = self.pointer while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': start -= 1 if self.pointer-start > max_length/2-1: head = ' ... ' start += 5 break tail = '' end = self.pointer while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': end += 1 if end-self.pointer > max_length/2-1: tail = ' ... ' end -= 5 break snippet = self.buffer[start:end] return ' '*indent + head + snippet + tail + '\n' \ + ' '*(indent+self.pointer-start+len(head)) + '^' def __str__(self): snippet = self.get_snippet() where = " in \"%s\", line %d, column %d" \ % (self.name, self.line+1, self.column+1) if snippet is not None: where += ":\n"+snippet return where class YAMLError(Exception): pass class MarkedYAMLError(YAMLError): def __init__(self, context=None, context_mark=None, problem=None, problem_mark=None, note=None): self.context = context self.context_mark = context_mark self.problem = problem self.problem_mark = problem_mark self.note = note def __str__(self): lines = [] if self.context is not None: lines.append(self.context) if self.context_mark is not None \ and (self.problem is None or self.problem_mark is None or self.context_mark.name != self.problem_mark.name or self.context_mark.line != self.problem_mark.line or self.context_mark.column != self.problem_mark.column): lines.append(str(self.context_mark)) if self.problem is not None: lines.append(self.problem) if self.problem_mark is not None: lines.append(str(self.problem_mark)) if self.note is not None: lines.append(self.note) return '\n'.join(lines)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/error.py
error.py
__all__ = ['BaseLoader', 'FullLoader', 'SafeLoader', 'Loader', 'UnsafeLoader'] from .reader import * from .scanner import * from .parser import * from .composer import * from .constructor import * from .resolver import * class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) BaseConstructor.__init__(self) BaseResolver.__init__(self) class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) FullConstructor.__init__(self) Resolver.__init__(self) class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) SafeConstructor.__init__(self) Resolver.__init__(self) class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) Constructor.__init__(self) Resolver.__init__(self) # UnsafeLoader is the same as Loader (which is and was always unsafe on # untrusted input). Use of either Loader or UnsafeLoader should be rare, since # FullLoad should be able to load almost all YAML safely. Loader is left intact # to ensure backwards compatibility. class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) Constructor.__init__(self) Resolver.__init__(self)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/loader.py
loader.py
__all__ = ['Scanner', 'ScannerError'] from .error import MarkedYAMLError from .tokens import * class ScannerError(MarkedYAMLError): pass class SimpleKey: # See below simple keys treatment. def __init__(self, token_number, required, index, line, column, mark): self.token_number = token_number self.required = required self.index = index self.line = line self.column = column self.mark = mark class Scanner: def __init__(self): """Initialize the scanner.""" # It is assumed that Scanner and Reader will have a common descendant. # Reader do the dirty work of checking for BOM and converting the # input data to Unicode. It also adds NUL to the end. # # Reader supports the following methods # self.peek(i=0) # peek the next i-th character # self.prefix(l=1) # peek the next l characters # self.forward(l=1) # read the next l characters and move the pointer. # Had we reached the end of the stream? self.done = False # The number of unclosed '{' and '['. `flow_level == 0` means block # context. self.flow_level = 0 # List of processed tokens that are not yet emitted. self.tokens = [] # Add the STREAM-START token. self.fetch_stream_start() # Number of tokens that were emitted through the `get_token` method. self.tokens_taken = 0 # The current indentation level. self.indent = -1 # Past indentation levels. self.indents = [] # Variables related to simple keys treatment. # A simple key is a key that is not denoted by the '?' indicator. # Example of simple keys: # --- # block simple key: value # ? not a simple key: # : { flow simple key: value } # We emit the KEY token before all keys, so when we find a potential # simple key, we try to locate the corresponding ':' indicator. # Simple keys should be limited to a single line and 1024 characters. # Can a simple key start at the current position? A simple key may # start: # - at the beginning of the line, not counting indentation spaces # (in block context), # - after '{', '[', ',' (in the flow context), # - after '?', ':', '-' (in the block context). # In the block context, this flag also signifies if a block collection # may start at the current position. self.allow_simple_key = True # Keep track of possible simple keys. This is a dictionary. The key # is `flow_level`; there can be no more that one possible simple key # for each level. The value is a SimpleKey record: # (token_number, required, index, line, column, mark) # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow), # '[', or '{' tokens. self.possible_simple_keys = {} # Public methods. def check_token(self, *choices): # Check if the next token is one of the given types. while self.need_more_tokens(): self.fetch_more_tokens() if self.tokens: if not choices: return True for choice in choices: if isinstance(self.tokens[0], choice): return True return False def peek_token(self): # Return the next token, but do not delete if from the queue. # Return None if no more tokens. while self.need_more_tokens(): self.fetch_more_tokens() if self.tokens: return self.tokens[0] else: return None def get_token(self): # Return the next token. while self.need_more_tokens(): self.fetch_more_tokens() if self.tokens: self.tokens_taken += 1 return self.tokens.pop(0) # Private methods. def need_more_tokens(self): if self.done: return False if not self.tokens: return True # The current token may be a potential simple key, so we # need to look further. self.stale_possible_simple_keys() if self.next_possible_simple_key() == self.tokens_taken: return True def fetch_more_tokens(self): # Eat whitespaces and comments until we reach the next token. self.scan_to_next_token() # Remove obsolete possible simple keys. self.stale_possible_simple_keys() # Compare the current indentation and column. It may add some tokens # and decrease the current indentation level. self.unwind_indent(self.column) # Peek the next character. ch = self.peek() # Is it the end of stream? if ch == '\0': return self.fetch_stream_end() # Is it a directive? if ch == '%' and self.check_directive(): return self.fetch_directive() # Is it the document start? if ch == '-' and self.check_document_start(): return self.fetch_document_start() # Is it the document end? if ch == '.' and self.check_document_end(): return self.fetch_document_end() # TODO: support for BOM within a stream. #if ch == '\uFEFF': # return self.fetch_bom() <-- issue BOMToken # Note: the order of the following checks is NOT significant. # Is it the flow sequence start indicator? if ch == '[': return self.fetch_flow_sequence_start() # Is it the flow mapping start indicator? if ch == '{': return self.fetch_flow_mapping_start() # Is it the flow sequence end indicator? if ch == ']': return self.fetch_flow_sequence_end() # Is it the flow mapping end indicator? if ch == '}': return self.fetch_flow_mapping_end() # Is it the flow entry indicator? if ch == ',': return self.fetch_flow_entry() # Is it the block entry indicator? if ch == '-' and self.check_block_entry(): return self.fetch_block_entry() # Is it the key indicator? if ch == '?' and self.check_key(): return self.fetch_key() # Is it the value indicator? if ch == ':' and self.check_value(): return self.fetch_value() # Is it an alias? if ch == '*': return self.fetch_alias() # Is it an anchor? if ch == '&': return self.fetch_anchor() # Is it a tag? if ch == '!': return self.fetch_tag() # Is it a literal scalar? if ch == '|' and not self.flow_level: return self.fetch_literal() # Is it a folded scalar? if ch == '>' and not self.flow_level: return self.fetch_folded() # Is it a single quoted scalar? if ch == '\'': return self.fetch_single() # Is it a double quoted scalar? if ch == '\"': return self.fetch_double() # It must be a plain scalar then. if self.check_plain(): return self.fetch_plain() # No? It's an error. Let's produce a nice error message. raise ScannerError("while scanning for the next token", None, "found character %r that cannot start any token" % ch, self.get_mark()) # Simple keys treatment. def next_possible_simple_key(self): # Return the number of the nearest possible simple key. Actually we # don't need to loop through the whole dictionary. We may replace it # with the following code: # if not self.possible_simple_keys: # return None # return self.possible_simple_keys[ # min(self.possible_simple_keys.keys())].token_number min_token_number = None for level in self.possible_simple_keys: key = self.possible_simple_keys[level] if min_token_number is None or key.token_number < min_token_number: min_token_number = key.token_number return min_token_number def stale_possible_simple_keys(self): # Remove entries that are no longer possible simple keys. According to # the YAML specification, simple keys # - should be limited to a single line, # - should be no longer than 1024 characters. # Disabling this procedure will allow simple keys of any length and # height (may cause problems if indentation is broken though). for level in list(self.possible_simple_keys): key = self.possible_simple_keys[level] if key.line != self.line \ or self.index-key.index > 1024: if key.required: raise ScannerError("while scanning a simple key", key.mark, "could not find expected ':'", self.get_mark()) del self.possible_simple_keys[level] def save_possible_simple_key(self): # The next token may start a simple key. We check if it's possible # and save its position. This function is called for # ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'. # Check if a simple key is required at the current position. required = not self.flow_level and self.indent == self.column # The next token might be a simple key. Let's save it's number and # position. if self.allow_simple_key: self.remove_possible_simple_key() token_number = self.tokens_taken+len(self.tokens) key = SimpleKey(token_number, required, self.index, self.line, self.column, self.get_mark()) self.possible_simple_keys[self.flow_level] = key def remove_possible_simple_key(self): # Remove the saved possible key position at the current flow level. if self.flow_level in self.possible_simple_keys: key = self.possible_simple_keys[self.flow_level] if key.required: raise ScannerError("while scanning a simple key", key.mark, "could not find expected ':'", self.get_mark()) del self.possible_simple_keys[self.flow_level] # Indentation functions. def unwind_indent(self, column): ## In flow context, tokens should respect indentation. ## Actually the condition should be `self.indent >= column` according to ## the spec. But this condition will prohibit intuitively correct ## constructions such as ## key : { ## } #if self.flow_level and self.indent > column: # raise ScannerError(None, None, # "invalid indentation or unclosed '[' or '{'", # self.get_mark()) # In the flow context, indentation is ignored. We make the scanner less # restrictive then specification requires. if self.flow_level: return # In block context, we may need to issue the BLOCK-END tokens. while self.indent > column: mark = self.get_mark() self.indent = self.indents.pop() self.tokens.append(BlockEndToken(mark, mark)) def add_indent(self, column): # Check if we need to increase indentation. if self.indent < column: self.indents.append(self.indent) self.indent = column return True return False # Fetchers. def fetch_stream_start(self): # We always add STREAM-START as the first token and STREAM-END as the # last token. # Read the token. mark = self.get_mark() # Add STREAM-START. self.tokens.append(StreamStartToken(mark, mark, encoding=self.encoding)) def fetch_stream_end(self): # Set the current indentation to -1. self.unwind_indent(-1) # Reset simple keys. self.remove_possible_simple_key() self.allow_simple_key = False self.possible_simple_keys = {} # Read the token. mark = self.get_mark() # Add STREAM-END. self.tokens.append(StreamEndToken(mark, mark)) # The steam is finished. self.done = True def fetch_directive(self): # Set the current indentation to -1. self.unwind_indent(-1) # Reset simple keys. self.remove_possible_simple_key() self.allow_simple_key = False # Scan and add DIRECTIVE. self.tokens.append(self.scan_directive()) def fetch_document_start(self): self.fetch_document_indicator(DocumentStartToken) def fetch_document_end(self): self.fetch_document_indicator(DocumentEndToken) def fetch_document_indicator(self, TokenClass): # Set the current indentation to -1. self.unwind_indent(-1) # Reset simple keys. Note that there could not be a block collection # after '---'. self.remove_possible_simple_key() self.allow_simple_key = False # Add DOCUMENT-START or DOCUMENT-END. start_mark = self.get_mark() self.forward(3) end_mark = self.get_mark() self.tokens.append(TokenClass(start_mark, end_mark)) def fetch_flow_sequence_start(self): self.fetch_flow_collection_start(FlowSequenceStartToken) def fetch_flow_mapping_start(self): self.fetch_flow_collection_start(FlowMappingStartToken) def fetch_flow_collection_start(self, TokenClass): # '[' and '{' may start a simple key. self.save_possible_simple_key() # Increase the flow level. self.flow_level += 1 # Simple keys are allowed after '[' and '{'. self.allow_simple_key = True # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START. start_mark = self.get_mark() self.forward() end_mark = self.get_mark() self.tokens.append(TokenClass(start_mark, end_mark)) def fetch_flow_sequence_end(self): self.fetch_flow_collection_end(FlowSequenceEndToken) def fetch_flow_mapping_end(self): self.fetch_flow_collection_end(FlowMappingEndToken) def fetch_flow_collection_end(self, TokenClass): # Reset possible simple key on the current level. self.remove_possible_simple_key() # Decrease the flow level. self.flow_level -= 1 # No simple keys after ']' or '}'. self.allow_simple_key = False # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END. start_mark = self.get_mark() self.forward() end_mark = self.get_mark() self.tokens.append(TokenClass(start_mark, end_mark)) def fetch_flow_entry(self): # Simple keys are allowed after ','. self.allow_simple_key = True # Reset possible simple key on the current level. self.remove_possible_simple_key() # Add FLOW-ENTRY. start_mark = self.get_mark() self.forward() end_mark = self.get_mark() self.tokens.append(FlowEntryToken(start_mark, end_mark)) def fetch_block_entry(self): # Block context needs additional checks. if not self.flow_level: # Are we allowed to start a new entry? if not self.allow_simple_key: raise ScannerError(None, None, "sequence entries are not allowed here", self.get_mark()) # We may need to add BLOCK-SEQUENCE-START. if self.add_indent(self.column): mark = self.get_mark() self.tokens.append(BlockSequenceStartToken(mark, mark)) # It's an error for the block entry to occur in the flow context, # but we let the parser detect this. else: pass # Simple keys are allowed after '-'. self.allow_simple_key = True # Reset possible simple key on the current level. self.remove_possible_simple_key() # Add BLOCK-ENTRY. start_mark = self.get_mark() self.forward() end_mark = self.get_mark() self.tokens.append(BlockEntryToken(start_mark, end_mark)) def fetch_key(self): # Block context needs additional checks. if not self.flow_level: # Are we allowed to start a key (not necessary a simple)? if not self.allow_simple_key: raise ScannerError(None, None, "mapping keys are not allowed here", self.get_mark()) # We may need to add BLOCK-MAPPING-START. if self.add_indent(self.column): mark = self.get_mark() self.tokens.append(BlockMappingStartToken(mark, mark)) # Simple keys are allowed after '?' in the block context. self.allow_simple_key = not self.flow_level # Reset possible simple key on the current level. self.remove_possible_simple_key() # Add KEY. start_mark = self.get_mark() self.forward() end_mark = self.get_mark() self.tokens.append(KeyToken(start_mark, end_mark)) def fetch_value(self): # Do we determine a simple key? if self.flow_level in self.possible_simple_keys: # Add KEY. key = self.possible_simple_keys[self.flow_level] del self.possible_simple_keys[self.flow_level] self.tokens.insert(key.token_number-self.tokens_taken, KeyToken(key.mark, key.mark)) # If this key starts a new block mapping, we need to add # BLOCK-MAPPING-START. if not self.flow_level: if self.add_indent(key.column): self.tokens.insert(key.token_number-self.tokens_taken, BlockMappingStartToken(key.mark, key.mark)) # There cannot be two simple keys one after another. self.allow_simple_key = False # It must be a part of a complex key. else: # Block context needs additional checks. # (Do we really need them? They will be caught by the parser # anyway.) if not self.flow_level: # We are allowed to start a complex value if and only if # we can start a simple key. if not self.allow_simple_key: raise ScannerError(None, None, "mapping values are not allowed here", self.get_mark()) # If this value starts a new block mapping, we need to add # BLOCK-MAPPING-START. It will be detected as an error later by # the parser. if not self.flow_level: if self.add_indent(self.column): mark = self.get_mark() self.tokens.append(BlockMappingStartToken(mark, mark)) # Simple keys are allowed after ':' in the block context. self.allow_simple_key = not self.flow_level # Reset possible simple key on the current level. self.remove_possible_simple_key() # Add VALUE. start_mark = self.get_mark() self.forward() end_mark = self.get_mark() self.tokens.append(ValueToken(start_mark, end_mark)) def fetch_alias(self): # ALIAS could be a simple key. self.save_possible_simple_key() # No simple keys after ALIAS. self.allow_simple_key = False # Scan and add ALIAS. self.tokens.append(self.scan_anchor(AliasToken)) def fetch_anchor(self): # ANCHOR could start a simple key. self.save_possible_simple_key() # No simple keys after ANCHOR. self.allow_simple_key = False # Scan and add ANCHOR. self.tokens.append(self.scan_anchor(AnchorToken)) def fetch_tag(self): # TAG could start a simple key. self.save_possible_simple_key() # No simple keys after TAG. self.allow_simple_key = False # Scan and add TAG. self.tokens.append(self.scan_tag()) def fetch_literal(self): self.fetch_block_scalar(style='|') def fetch_folded(self): self.fetch_block_scalar(style='>') def fetch_block_scalar(self, style): # A simple key may follow a block scalar. self.allow_simple_key = True # Reset possible simple key on the current level. self.remove_possible_simple_key() # Scan and add SCALAR. self.tokens.append(self.scan_block_scalar(style)) def fetch_single(self): self.fetch_flow_scalar(style='\'') def fetch_double(self): self.fetch_flow_scalar(style='"') def fetch_flow_scalar(self, style): # A flow scalar could be a simple key. self.save_possible_simple_key() # No simple keys after flow scalars. self.allow_simple_key = False # Scan and add SCALAR. self.tokens.append(self.scan_flow_scalar(style)) def fetch_plain(self): # A plain scalar could be a simple key. self.save_possible_simple_key() # No simple keys after plain scalars. But note that `scan_plain` will # change this flag if the scan is finished at the beginning of the # line. self.allow_simple_key = False # Scan and add SCALAR. May change `allow_simple_key`. self.tokens.append(self.scan_plain()) # Checkers. def check_directive(self): # DIRECTIVE: ^ '%' ... # The '%' indicator is already checked. if self.column == 0: return True def check_document_start(self): # DOCUMENT-START: ^ '---' (' '|'\n') if self.column == 0: if self.prefix(3) == '---' \ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return True def check_document_end(self): # DOCUMENT-END: ^ '...' (' '|'\n') if self.column == 0: if self.prefix(3) == '...' \ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return True def check_block_entry(self): # BLOCK-ENTRY: '-' (' '|'\n') return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' def check_key(self): # KEY(flow context): '?' if self.flow_level: return True # KEY(block context): '?' (' '|'\n') else: return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' def check_value(self): # VALUE(flow context): ':' if self.flow_level: return True # VALUE(block context): ':' (' '|'\n') else: return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' def check_plain(self): # A plain scalar may start with any non-space character except: # '-', '?', ':', ',', '[', ']', '{', '}', # '#', '&', '*', '!', '|', '>', '\'', '\"', # '%', '@', '`'. # # It may also start with # '-', '?', ':' # if it is followed by a non-space character. # # Note that we limit the last rule to the block context (except the # '-' character) because we want the flow context to be space # independent. ch = self.peek() return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \ or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029' and (ch == '-' or (not self.flow_level and ch in '?:'))) # Scanners. def scan_to_next_token(self): # We ignore spaces, line breaks and comments. # If we find a line break in the block context, we set the flag # `allow_simple_key` on. # The byte order mark is stripped if it's the first character in the # stream. We do not yet support BOM inside the stream as the # specification requires. Any such mark will be considered as a part # of the document. # # TODO: We need to make tab handling rules more sane. A good rule is # Tabs cannot precede tokens # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END, # KEY(block), VALUE(block), BLOCK-ENTRY # So the checking code is # if <TAB>: # self.allow_simple_keys = False # We also need to add the check for `allow_simple_keys == True` to # `unwind_indent` before issuing BLOCK-END. # Scanners for block, flow, and plain scalars need to be modified. if self.index == 0 and self.peek() == '\uFEFF': self.forward() found = False while not found: while self.peek() == ' ': self.forward() if self.peek() == '#': while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() if self.scan_line_break(): if not self.flow_level: self.allow_simple_key = True else: found = True def scan_directive(self): # See the specification for details. start_mark = self.get_mark() self.forward() name = self.scan_directive_name(start_mark) value = None if name == 'YAML': value = self.scan_yaml_directive_value(start_mark) end_mark = self.get_mark() elif name == 'TAG': value = self.scan_tag_directive_value(start_mark) end_mark = self.get_mark() else: end_mark = self.get_mark() while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() self.scan_directive_ignored_line(start_mark) return DirectiveToken(name, value, start_mark, end_mark) def scan_directive_name(self, start_mark): # See the specification for details. length = 0 ch = self.peek(length) while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-_': length += 1 ch = self.peek(length) if not length: raise ScannerError("while scanning a directive", start_mark, "expected alphabetic or numeric character, but found %r" % ch, self.get_mark()) value = self.prefix(length) self.forward(length) ch = self.peek() if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected alphabetic or numeric character, but found %r" % ch, self.get_mark()) return value def scan_yaml_directive_value(self, start_mark): # See the specification for details. while self.peek() == ' ': self.forward() major = self.scan_yaml_directive_number(start_mark) if self.peek() != '.': raise ScannerError("while scanning a directive", start_mark, "expected a digit or '.', but found %r" % self.peek(), self.get_mark()) self.forward() minor = self.scan_yaml_directive_number(start_mark) if self.peek() not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected a digit or ' ', but found %r" % self.peek(), self.get_mark()) return (major, minor) def scan_yaml_directive_number(self, start_mark): # See the specification for details. ch = self.peek() if not ('0' <= ch <= '9'): raise ScannerError("while scanning a directive", start_mark, "expected a digit, but found %r" % ch, self.get_mark()) length = 0 while '0' <= self.peek(length) <= '9': length += 1 value = int(self.prefix(length)) self.forward(length) return value def scan_tag_directive_value(self, start_mark): # See the specification for details. while self.peek() == ' ': self.forward() handle = self.scan_tag_directive_handle(start_mark) while self.peek() == ' ': self.forward() prefix = self.scan_tag_directive_prefix(start_mark) return (handle, prefix) def scan_tag_directive_handle(self, start_mark): # See the specification for details. value = self.scan_tag_handle('directive', start_mark) ch = self.peek() if ch != ' ': raise ScannerError("while scanning a directive", start_mark, "expected ' ', but found %r" % ch, self.get_mark()) return value def scan_tag_directive_prefix(self, start_mark): # See the specification for details. value = self.scan_tag_uri('directive', start_mark) ch = self.peek() if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected ' ', but found %r" % ch, self.get_mark()) return value def scan_directive_ignored_line(self, start_mark): # See the specification for details. while self.peek() == ' ': self.forward() if self.peek() == '#': while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() ch = self.peek() if ch not in '\0\r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected a comment or a line break, but found %r" % ch, self.get_mark()) self.scan_line_break() def scan_anchor(self, TokenClass): # The specification does not restrict characters for anchors and # aliases. This may lead to problems, for instance, the document: # [ *alias, value ] # can be interpreted in two ways, as # [ "value" ] # and # [ *alias , "value" ] # Therefore we restrict aliases to numbers and ASCII letters. start_mark = self.get_mark() indicator = self.peek() if indicator == '*': name = 'alias' else: name = 'anchor' self.forward() length = 0 ch = self.peek(length) while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-_': length += 1 ch = self.peek(length) if not length: raise ScannerError("while scanning an %s" % name, start_mark, "expected alphabetic or numeric character, but found %r" % ch, self.get_mark()) value = self.prefix(length) self.forward(length) ch = self.peek() if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`': raise ScannerError("while scanning an %s" % name, start_mark, "expected alphabetic or numeric character, but found %r" % ch, self.get_mark()) end_mark = self.get_mark() return TokenClass(value, start_mark, end_mark) def scan_tag(self): # See the specification for details. start_mark = self.get_mark() ch = self.peek(1) if ch == '<': handle = None self.forward(2) suffix = self.scan_tag_uri('tag', start_mark) if self.peek() != '>': raise ScannerError("while parsing a tag", start_mark, "expected '>', but found %r" % self.peek(), self.get_mark()) self.forward() elif ch in '\0 \t\r\n\x85\u2028\u2029': handle = None suffix = '!' self.forward() else: length = 1 use_handle = False while ch not in '\0 \r\n\x85\u2028\u2029': if ch == '!': use_handle = True break length += 1 ch = self.peek(length) handle = '!' if use_handle: handle = self.scan_tag_handle('tag', start_mark) else: handle = '!' self.forward() suffix = self.scan_tag_uri('tag', start_mark) ch = self.peek() if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a tag", start_mark, "expected ' ', but found %r" % ch, self.get_mark()) value = (handle, suffix) end_mark = self.get_mark() return TagToken(value, start_mark, end_mark) def scan_block_scalar(self, style): # See the specification for details. if style == '>': folded = True else: folded = False chunks = [] start_mark = self.get_mark() # Scan the header. self.forward() chomping, increment = self.scan_block_scalar_indicators(start_mark) self.scan_block_scalar_ignored_line(start_mark) # Determine the indentation level and go to the first non-empty line. min_indent = self.indent+1 if min_indent < 1: min_indent = 1 if increment is None: breaks, max_indent, end_mark = self.scan_block_scalar_indentation() indent = max(min_indent, max_indent) else: indent = min_indent+increment-1 breaks, end_mark = self.scan_block_scalar_breaks(indent) line_break = '' # Scan the inner part of the block scalar. while self.column == indent and self.peek() != '\0': chunks.extend(breaks) leading_non_space = self.peek() not in ' \t' length = 0 while self.peek(length) not in '\0\r\n\x85\u2028\u2029': length += 1 chunks.append(self.prefix(length)) self.forward(length) line_break = self.scan_line_break() breaks, end_mark = self.scan_block_scalar_breaks(indent) if self.column == indent and self.peek() != '\0': # Unfortunately, folding rules are ambiguous. # # This is the folding according to the specification: if folded and line_break == '\n' \ and leading_non_space and self.peek() not in ' \t': if not breaks: chunks.append(' ') else: chunks.append(line_break) # This is Clark Evans's interpretation (also in the spec # examples): # #if folded and line_break == '\n': # if not breaks: # if self.peek() not in ' \t': # chunks.append(' ') # else: # chunks.append(line_break) #else: # chunks.append(line_break) else: break # Chomp the tail. if chomping is not False: chunks.append(line_break) if chomping is True: chunks.extend(breaks) # We are done. return ScalarToken(''.join(chunks), False, start_mark, end_mark, style) def scan_block_scalar_indicators(self, start_mark): # See the specification for details. chomping = None increment = None ch = self.peek() if ch in '+-': if ch == '+': chomping = True else: chomping = False self.forward() ch = self.peek() if ch in '0123456789': increment = int(ch) if increment == 0: raise ScannerError("while scanning a block scalar", start_mark, "expected indentation indicator in the range 1-9, but found 0", self.get_mark()) self.forward() elif ch in '0123456789': increment = int(ch) if increment == 0: raise ScannerError("while scanning a block scalar", start_mark, "expected indentation indicator in the range 1-9, but found 0", self.get_mark()) self.forward() ch = self.peek() if ch in '+-': if ch == '+': chomping = True else: chomping = False self.forward() ch = self.peek() if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a block scalar", start_mark, "expected chomping or indentation indicators, but found %r" % ch, self.get_mark()) return chomping, increment def scan_block_scalar_ignored_line(self, start_mark): # See the specification for details. while self.peek() == ' ': self.forward() if self.peek() == '#': while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() ch = self.peek() if ch not in '\0\r\n\x85\u2028\u2029': raise ScannerError("while scanning a block scalar", start_mark, "expected a comment or a line break, but found %r" % ch, self.get_mark()) self.scan_line_break() def scan_block_scalar_indentation(self): # See the specification for details. chunks = [] max_indent = 0 end_mark = self.get_mark() while self.peek() in ' \r\n\x85\u2028\u2029': if self.peek() != ' ': chunks.append(self.scan_line_break()) end_mark = self.get_mark() else: self.forward() if self.column > max_indent: max_indent = self.column return chunks, max_indent, end_mark def scan_block_scalar_breaks(self, indent): # See the specification for details. chunks = [] end_mark = self.get_mark() while self.column < indent and self.peek() == ' ': self.forward() while self.peek() in '\r\n\x85\u2028\u2029': chunks.append(self.scan_line_break()) end_mark = self.get_mark() while self.column < indent and self.peek() == ' ': self.forward() return chunks, end_mark def scan_flow_scalar(self, style): # See the specification for details. # Note that we loose indentation rules for quoted scalars. Quoted # scalars don't need to adhere indentation because " and ' clearly # mark the beginning and the end of them. Therefore we are less # restrictive then the specification requires. We only need to check # that document separators are not included in scalars. if style == '"': double = True else: double = False chunks = [] start_mark = self.get_mark() quote = self.peek() self.forward() chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) while self.peek() != quote: chunks.extend(self.scan_flow_scalar_spaces(double, start_mark)) chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) self.forward() end_mark = self.get_mark() return ScalarToken(''.join(chunks), False, start_mark, end_mark, style) ESCAPE_REPLACEMENTS = { '0': '\0', 'a': '\x07', 'b': '\x08', 't': '\x09', '\t': '\x09', 'n': '\x0A', 'v': '\x0B', 'f': '\x0C', 'r': '\x0D', 'e': '\x1B', ' ': '\x20', '\"': '\"', '\\': '\\', '/': '/', 'N': '\x85', '_': '\xA0', 'L': '\u2028', 'P': '\u2029', } ESCAPE_CODES = { 'x': 2, 'u': 4, 'U': 8, } def scan_flow_scalar_non_spaces(self, double, start_mark): # See the specification for details. chunks = [] while True: length = 0 while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029': length += 1 if length: chunks.append(self.prefix(length)) self.forward(length) ch = self.peek() if not double and ch == '\'' and self.peek(1) == '\'': chunks.append('\'') self.forward(2) elif (double and ch == '\'') or (not double and ch in '\"\\'): chunks.append(ch) self.forward() elif double and ch == '\\': self.forward() ch = self.peek() if ch in self.ESCAPE_REPLACEMENTS: chunks.append(self.ESCAPE_REPLACEMENTS[ch]) self.forward() elif ch in self.ESCAPE_CODES: length = self.ESCAPE_CODES[ch] self.forward() for k in range(length): if self.peek(k) not in '0123456789ABCDEFabcdef': raise ScannerError("while scanning a double-quoted scalar", start_mark, "expected escape sequence of %d hexadecimal numbers, but found %r" % (length, self.peek(k)), self.get_mark()) code = int(self.prefix(length), 16) chunks.append(chr(code)) self.forward(length) elif ch in '\r\n\x85\u2028\u2029': self.scan_line_break() chunks.extend(self.scan_flow_scalar_breaks(double, start_mark)) else: raise ScannerError("while scanning a double-quoted scalar", start_mark, "found unknown escape character %r" % ch, self.get_mark()) else: return chunks def scan_flow_scalar_spaces(self, double, start_mark): # See the specification for details. chunks = [] length = 0 while self.peek(length) in ' \t': length += 1 whitespaces = self.prefix(length) self.forward(length) ch = self.peek() if ch == '\0': raise ScannerError("while scanning a quoted scalar", start_mark, "found unexpected end of stream", self.get_mark()) elif ch in '\r\n\x85\u2028\u2029': line_break = self.scan_line_break() breaks = self.scan_flow_scalar_breaks(double, start_mark) if line_break != '\n': chunks.append(line_break) elif not breaks: chunks.append(' ') chunks.extend(breaks) else: chunks.append(whitespaces) return chunks def scan_flow_scalar_breaks(self, double, start_mark): # See the specification for details. chunks = [] while True: # Instead of checking indentation, we check for document # separators. prefix = self.prefix(3) if (prefix == '---' or prefix == '...') \ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': raise ScannerError("while scanning a quoted scalar", start_mark, "found unexpected document separator", self.get_mark()) while self.peek() in ' \t': self.forward() if self.peek() in '\r\n\x85\u2028\u2029': chunks.append(self.scan_line_break()) else: return chunks def scan_plain(self): # See the specification for details. # We add an additional restriction for the flow context: # plain scalars in the flow context cannot contain ',' or '?'. # We also keep track of the `allow_simple_key` flag here. # Indentation rules are loosed for the flow context. chunks = [] start_mark = self.get_mark() end_mark = start_mark indent = self.indent+1 # We allow zero indentation for scalars, but then we need to check for # document separators at the beginning of the line. #if indent == 0: # indent = 1 spaces = [] while True: length = 0 if self.peek() == '#': break while True: ch = self.peek(length) if ch in '\0 \t\r\n\x85\u2028\u2029' \ or (ch == ':' and self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029' + (u',[]{}' if self.flow_level else u''))\ or (self.flow_level and ch in ',?[]{}'): break length += 1 if length == 0: break self.allow_simple_key = False chunks.extend(spaces) chunks.append(self.prefix(length)) self.forward(length) end_mark = self.get_mark() spaces = self.scan_plain_spaces(indent, start_mark) if not spaces or self.peek() == '#' \ or (not self.flow_level and self.column < indent): break return ScalarToken(''.join(chunks), True, start_mark, end_mark) def scan_plain_spaces(self, indent, start_mark): # See the specification for details. # The specification is really confusing about tabs in plain scalars. # We just forbid them completely. Do not use tabs in YAML! chunks = [] length = 0 while self.peek(length) in ' ': length += 1 whitespaces = self.prefix(length) self.forward(length) ch = self.peek() if ch in '\r\n\x85\u2028\u2029': line_break = self.scan_line_break() self.allow_simple_key = True prefix = self.prefix(3) if (prefix == '---' or prefix == '...') \ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return breaks = [] while self.peek() in ' \r\n\x85\u2028\u2029': if self.peek() == ' ': self.forward() else: breaks.append(self.scan_line_break()) prefix = self.prefix(3) if (prefix == '---' or prefix == '...') \ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return if line_break != '\n': chunks.append(line_break) elif not breaks: chunks.append(' ') chunks.extend(breaks) elif whitespaces: chunks.append(whitespaces) return chunks def scan_tag_handle(self, name, start_mark): # See the specification for details. # For some strange reasons, the specification does not allow '_' in # tag handles. I have allowed it anyway. ch = self.peek() if ch != '!': raise ScannerError("while scanning a %s" % name, start_mark, "expected '!', but found %r" % ch, self.get_mark()) length = 1 ch = self.peek(length) if ch != ' ': while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-_': length += 1 ch = self.peek(length) if ch != '!': self.forward(length) raise ScannerError("while scanning a %s" % name, start_mark, "expected '!', but found %r" % ch, self.get_mark()) length += 1 value = self.prefix(length) self.forward(length) return value def scan_tag_uri(self, name, start_mark): # See the specification for details. # Note: we do not check if URI is well-formed. chunks = [] length = 0 ch = self.peek(length) while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ or ch in '-;/?:@&=+$,_.!~*\'()[]%': if ch == '%': chunks.append(self.prefix(length)) self.forward(length) length = 0 chunks.append(self.scan_uri_escapes(name, start_mark)) else: length += 1 ch = self.peek(length) if length: chunks.append(self.prefix(length)) self.forward(length) length = 0 if not chunks: raise ScannerError("while parsing a %s" % name, start_mark, "expected URI, but found %r" % ch, self.get_mark()) return ''.join(chunks) def scan_uri_escapes(self, name, start_mark): # See the specification for details. codes = [] mark = self.get_mark() while self.peek() == '%': self.forward() for k in range(2): if self.peek(k) not in '0123456789ABCDEFabcdef': raise ScannerError("while scanning a %s" % name, start_mark, "expected URI escape sequence of 2 hexadecimal numbers, but found %r" % self.peek(k), self.get_mark()) codes.append(int(self.prefix(2), 16)) self.forward(2) try: value = bytes(codes).decode('utf-8') except UnicodeDecodeError as exc: raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark) return value def scan_line_break(self): # Transforms: # '\r\n' : '\n' # '\r' : '\n' # '\n' : '\n' # '\x85' : '\n' # '\u2028' : '\u2028' # '\u2029 : '\u2029' # default : '' ch = self.peek() if ch in '\r\n\x85': if self.prefix(2) == '\r\n': self.forward(2) else: self.forward() return '\n' elif ch in '\u2028\u2029': self.forward() return ch return ''
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/scanner.py
scanner.py
class Token(object): def __init__(self, start_mark, end_mark): self.start_mark = start_mark self.end_mark = end_mark def __repr__(self): attributes = [key for key in self.__dict__ if not key.endswith('_mark')] attributes.sort() arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) for key in attributes]) return '%s(%s)' % (self.__class__.__name__, arguments) #class BOMToken(Token): # id = '<byte order mark>' class DirectiveToken(Token): id = '<directive>' def __init__(self, name, value, start_mark, end_mark): self.name = name self.value = value self.start_mark = start_mark self.end_mark = end_mark class DocumentStartToken(Token): id = '<document start>' class DocumentEndToken(Token): id = '<document end>' class StreamStartToken(Token): id = '<stream start>' def __init__(self, start_mark=None, end_mark=None, encoding=None): self.start_mark = start_mark self.end_mark = end_mark self.encoding = encoding class StreamEndToken(Token): id = '<stream end>' class BlockSequenceStartToken(Token): id = '<block sequence start>' class BlockMappingStartToken(Token): id = '<block mapping start>' class BlockEndToken(Token): id = '<block end>' class FlowSequenceStartToken(Token): id = '[' class FlowMappingStartToken(Token): id = '{' class FlowSequenceEndToken(Token): id = ']' class FlowMappingEndToken(Token): id = '}' class KeyToken(Token): id = '?' class ValueToken(Token): id = ':' class BlockEntryToken(Token): id = '-' class FlowEntryToken(Token): id = ',' class AliasToken(Token): id = '<alias>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark class AnchorToken(Token): id = '<anchor>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark class TagToken(Token): id = '<tag>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark class ScalarToken(Token): id = '<scalar>' def __init__(self, value, plain, start_mark, end_mark, style=None): self.value = value self.plain = plain self.start_mark = start_mark self.end_mark = end_mark self.style = style
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/tokens.py
tokens.py
class Event(object): def __init__(self, start_mark=None, end_mark=None): self.start_mark = start_mark self.end_mark = end_mark def __repr__(self): attributes = [key for key in ['anchor', 'tag', 'implicit', 'value'] if hasattr(self, key)] arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) for key in attributes]) return '%s(%s)' % (self.__class__.__name__, arguments) class NodeEvent(Event): def __init__(self, anchor, start_mark=None, end_mark=None): self.anchor = anchor self.start_mark = start_mark self.end_mark = end_mark class CollectionStartEvent(NodeEvent): def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None, flow_style=None): self.anchor = anchor self.tag = tag self.implicit = implicit self.start_mark = start_mark self.end_mark = end_mark self.flow_style = flow_style class CollectionEndEvent(Event): pass # Implementations. class StreamStartEvent(Event): def __init__(self, start_mark=None, end_mark=None, encoding=None): self.start_mark = start_mark self.end_mark = end_mark self.encoding = encoding class StreamEndEvent(Event): pass class DocumentStartEvent(Event): def __init__(self, start_mark=None, end_mark=None, explicit=None, version=None, tags=None): self.start_mark = start_mark self.end_mark = end_mark self.explicit = explicit self.version = version self.tags = tags class DocumentEndEvent(Event): def __init__(self, start_mark=None, end_mark=None, explicit=None): self.start_mark = start_mark self.end_mark = end_mark self.explicit = explicit class AliasEvent(NodeEvent): pass class ScalarEvent(NodeEvent): def __init__(self, anchor, tag, implicit, value, start_mark=None, end_mark=None, style=None): self.anchor = anchor self.tag = tag self.implicit = implicit self.value = value self.start_mark = start_mark self.end_mark = end_mark self.style = style class SequenceStartEvent(CollectionStartEvent): pass class SequenceEndEvent(CollectionEndEvent): pass class MappingStartEvent(CollectionStartEvent): pass class MappingEndEvent(CollectionEndEvent): pass
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/events.py
events.py
__all__ = ['Reader', 'ReaderError'] from .error import YAMLError, Mark import codecs, re class ReaderError(YAMLError): def __init__(self, name, position, character, encoding, reason): self.name = name self.character = character self.position = position self.encoding = encoding self.reason = reason def __str__(self): if isinstance(self.character, bytes): return "'%s' codec can't decode byte #x%02x: %s\n" \ " in \"%s\", position %d" \ % (self.encoding, ord(self.character), self.reason, self.name, self.position) else: return "unacceptable character #x%04x: %s\n" \ " in \"%s\", position %d" \ % (self.character, self.reason, self.name, self.position) class Reader(object): # Reader: # - determines the data encoding and converts it to a unicode string, # - checks if characters are in allowed range, # - adds '\0' to the end. # Reader accepts # - a `bytes` object, # - a `str` object, # - a file-like object with its `read` method returning `str`, # - a file-like object with its `read` method returning `unicode`. # Yeah, it's ugly and slow. def __init__(self, stream): self.name = None self.stream = None self.stream_pointer = 0 self.eof = True self.buffer = '' self.pointer = 0 self.raw_buffer = None self.raw_decode = None self.encoding = None self.index = 0 self.line = 0 self.column = 0 if isinstance(stream, str): self.name = "<unicode string>" self.check_printable(stream) self.buffer = stream+'\0' elif isinstance(stream, bytes): self.name = "<byte string>" self.raw_buffer = stream self.determine_encoding() else: self.stream = stream self.name = getattr(stream, 'name', "<file>") self.eof = False self.raw_buffer = None self.determine_encoding() def peek(self, index=0): try: return self.buffer[self.pointer+index] except IndexError: self.update(index+1) return self.buffer[self.pointer+index] def prefix(self, length=1): if self.pointer+length >= len(self.buffer): self.update(length) return self.buffer[self.pointer:self.pointer+length] def forward(self, length=1): if self.pointer+length+1 >= len(self.buffer): self.update(length+1) while length: ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 if ch in '\n\x85\u2028\u2029' \ or (ch == '\r' and self.buffer[self.pointer] != '\n'): self.line += 1 self.column = 0 elif ch != '\uFEFF': self.column += 1 length -= 1 def get_mark(self): if self.stream is None: return Mark(self.name, self.index, self.line, self.column, self.buffer, self.pointer) else: return Mark(self.name, self.index, self.line, self.column, None, None) def determine_encoding(self): while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2): self.update_raw() if isinstance(self.raw_buffer, bytes): if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): self.raw_decode = codecs.utf_16_le_decode self.encoding = 'utf-16-le' elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE): self.raw_decode = codecs.utf_16_be_decode self.encoding = 'utf-16-be' else: self.raw_decode = codecs.utf_8_decode self.encoding = 'utf-8' self.update(1) NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]') def check_printable(self, data): match = self.NON_PRINTABLE.search(data) if match: character = match.group() position = self.index+(len(self.buffer)-self.pointer)+match.start() raise ReaderError(self.name, position, ord(character), 'unicode', "special characters are not allowed") def update(self, length): if self.raw_buffer is None: return self.buffer = self.buffer[self.pointer:] self.pointer = 0 while len(self.buffer) < length: if not self.eof: self.update_raw() if self.raw_decode is not None: try: data, converted = self.raw_decode(self.raw_buffer, 'strict', self.eof) except UnicodeDecodeError as exc: character = self.raw_buffer[exc.start] if self.stream is not None: position = self.stream_pointer-len(self.raw_buffer)+exc.start else: position = exc.start raise ReaderError(self.name, position, character, exc.encoding, exc.reason) else: data = self.raw_buffer converted = len(data) self.check_printable(data) self.buffer += data self.raw_buffer = self.raw_buffer[converted:] if self.eof: self.buffer += '\0' self.raw_buffer = None break def update_raw(self, size=4096): data = self.stream.read(size) if self.raw_buffer is None: self.raw_buffer = data else: self.raw_buffer += data self.stream_pointer += len(data) if not data: self.eof = True
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/reader.py
reader.py
__all__ = ['Parser', 'ParserError'] from .error import MarkedYAMLError from .tokens import * from .events import * from .scanner import * class ParserError(MarkedYAMLError): pass class Parser: # Since writing a recursive-descendant parser is a straightforward task, we # do not give many comments here. DEFAULT_TAGS = { '!': '!', '!!': 'tag:yaml.org,2002:', } def __init__(self): self.current_event = None self.yaml_version = None self.tag_handles = {} self.states = [] self.marks = [] self.state = self.parse_stream_start def dispose(self): # Reset the state attributes (to clear self-references) self.states = [] self.state = None def check_event(self, *choices): # Check the type of the next event. if self.current_event is None: if self.state: self.current_event = self.state() if self.current_event is not None: if not choices: return True for choice in choices: if isinstance(self.current_event, choice): return True return False def peek_event(self): # Get the next event. if self.current_event is None: if self.state: self.current_event = self.state() return self.current_event def get_event(self): # Get the next event and proceed further. if self.current_event is None: if self.state: self.current_event = self.state() value = self.current_event self.current_event = None return value # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END # implicit_document ::= block_node DOCUMENT-END* # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* def parse_stream_start(self): # Parse the stream start. token = self.get_token() event = StreamStartEvent(token.start_mark, token.end_mark, encoding=token.encoding) # Prepare the next state. self.state = self.parse_implicit_document_start return event def parse_implicit_document_start(self): # Parse an implicit document. if not self.check_token(DirectiveToken, DocumentStartToken, StreamEndToken): self.tag_handles = self.DEFAULT_TAGS token = self.peek_token() start_mark = end_mark = token.start_mark event = DocumentStartEvent(start_mark, end_mark, explicit=False) # Prepare the next state. self.states.append(self.parse_document_end) self.state = self.parse_block_node return event else: return self.parse_document_start() def parse_document_start(self): # Parse any extra document end indicators. while self.check_token(DocumentEndToken): self.get_token() # Parse an explicit document. if not self.check_token(StreamEndToken): token = self.peek_token() start_mark = token.start_mark version, tags = self.process_directives() if not self.check_token(DocumentStartToken): raise ParserError(None, None, "expected '<document start>', but found %r" % self.peek_token().id, self.peek_token().start_mark) token = self.get_token() end_mark = token.end_mark event = DocumentStartEvent(start_mark, end_mark, explicit=True, version=version, tags=tags) self.states.append(self.parse_document_end) self.state = self.parse_document_content else: # Parse the end of the stream. token = self.get_token() event = StreamEndEvent(token.start_mark, token.end_mark) assert not self.states assert not self.marks self.state = None return event def parse_document_end(self): # Parse the document end. token = self.peek_token() start_mark = end_mark = token.start_mark explicit = False if self.check_token(DocumentEndToken): token = self.get_token() end_mark = token.end_mark explicit = True event = DocumentEndEvent(start_mark, end_mark, explicit=explicit) # Prepare the next state. self.state = self.parse_document_start return event def parse_document_content(self): if self.check_token(DirectiveToken, DocumentStartToken, DocumentEndToken, StreamEndToken): event = self.process_empty_scalar(self.peek_token().start_mark) self.state = self.states.pop() return event else: return self.parse_block_node() def process_directives(self): self.yaml_version = None self.tag_handles = {} while self.check_token(DirectiveToken): token = self.get_token() if token.name == 'YAML': if self.yaml_version is not None: raise ParserError(None, None, "found duplicate YAML directive", token.start_mark) major, minor = token.value if major != 1: raise ParserError(None, None, "found incompatible YAML document (version 1.* is required)", token.start_mark) self.yaml_version = token.value elif token.name == 'TAG': handle, prefix = token.value if handle in self.tag_handles: raise ParserError(None, None, "duplicate tag handle %r" % handle, token.start_mark) self.tag_handles[handle] = prefix if self.tag_handles: value = self.yaml_version, self.tag_handles.copy() else: value = self.yaml_version, None for key in self.DEFAULT_TAGS: if key not in self.tag_handles: self.tag_handles[key] = self.DEFAULT_TAGS[key] return value # block_node_or_indentless_sequence ::= ALIAS # | properties (block_content | indentless_block_sequence)? # | block_content # | indentless_block_sequence # block_node ::= ALIAS # | properties block_content? # | block_content # flow_node ::= ALIAS # | properties flow_content? # | flow_content # properties ::= TAG ANCHOR? | ANCHOR TAG? # block_content ::= block_collection | flow_collection | SCALAR # flow_content ::= flow_collection | SCALAR # block_collection ::= block_sequence | block_mapping # flow_collection ::= flow_sequence | flow_mapping def parse_block_node(self): return self.parse_node(block=True) def parse_flow_node(self): return self.parse_node() def parse_block_node_or_indentless_sequence(self): return self.parse_node(block=True, indentless_sequence=True) def parse_node(self, block=False, indentless_sequence=False): if self.check_token(AliasToken): token = self.get_token() event = AliasEvent(token.value, token.start_mark, token.end_mark) self.state = self.states.pop() else: anchor = None tag = None start_mark = end_mark = tag_mark = None if self.check_token(AnchorToken): token = self.get_token() start_mark = token.start_mark end_mark = token.end_mark anchor = token.value if self.check_token(TagToken): token = self.get_token() tag_mark = token.start_mark end_mark = token.end_mark tag = token.value elif self.check_token(TagToken): token = self.get_token() start_mark = tag_mark = token.start_mark end_mark = token.end_mark tag = token.value if self.check_token(AnchorToken): token = self.get_token() end_mark = token.end_mark anchor = token.value if tag is not None: handle, suffix = tag if handle is not None: if handle not in self.tag_handles: raise ParserError("while parsing a node", start_mark, "found undefined tag handle %r" % handle, tag_mark) tag = self.tag_handles[handle]+suffix else: tag = suffix #if tag == '!': # raise ParserError("while parsing a node", start_mark, # "found non-specific tag '!'", tag_mark, # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.") if start_mark is None: start_mark = end_mark = self.peek_token().start_mark event = None implicit = (tag is None or tag == '!') if indentless_sequence and self.check_token(BlockEntryToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark) self.state = self.parse_indentless_sequence_entry else: if self.check_token(ScalarToken): token = self.get_token() end_mark = token.end_mark if (token.plain and tag is None) or tag == '!': implicit = (True, False) elif tag is None: implicit = (False, True) else: implicit = (False, False) event = ScalarEvent(anchor, tag, implicit, token.value, start_mark, end_mark, style=token.style) self.state = self.states.pop() elif self.check_token(FlowSequenceStartToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_sequence_first_entry elif self.check_token(FlowMappingStartToken): end_mark = self.peek_token().end_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_mapping_first_key elif block and self.check_token(BlockSequenceStartToken): end_mark = self.peek_token().start_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_sequence_first_entry elif block and self.check_token(BlockMappingStartToken): end_mark = self.peek_token().start_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_mapping_first_key elif anchor is not None or tag is not None: # Empty scalars are allowed even if a tag or an anchor is # specified. event = ScalarEvent(anchor, tag, (implicit, False), '', start_mark, end_mark) self.state = self.states.pop() else: if block: node = 'block' else: node = 'flow' token = self.peek_token() raise ParserError("while parsing a %s node" % node, start_mark, "expected the node content, but found %r" % token.id, token.start_mark) return event # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END def parse_block_sequence_first_entry(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_block_sequence_entry() def parse_block_sequence_entry(self): if self.check_token(BlockEntryToken): token = self.get_token() if not self.check_token(BlockEntryToken, BlockEndToken): self.states.append(self.parse_block_sequence_entry) return self.parse_block_node() else: self.state = self.parse_block_sequence_entry return self.process_empty_scalar(token.end_mark) if not self.check_token(BlockEndToken): token = self.peek_token() raise ParserError("while parsing a block collection", self.marks[-1], "expected <block end>, but found %r" % token.id, token.start_mark) token = self.get_token() event = SequenceEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event # indentless_sequence ::= (BLOCK-ENTRY block_node?)+ def parse_indentless_sequence_entry(self): if self.check_token(BlockEntryToken): token = self.get_token() if not self.check_token(BlockEntryToken, KeyToken, ValueToken, BlockEndToken): self.states.append(self.parse_indentless_sequence_entry) return self.parse_block_node() else: self.state = self.parse_indentless_sequence_entry return self.process_empty_scalar(token.end_mark) token = self.peek_token() event = SequenceEndEvent(token.start_mark, token.start_mark) self.state = self.states.pop() return event # block_mapping ::= BLOCK-MAPPING_START # ((KEY block_node_or_indentless_sequence?)? # (VALUE block_node_or_indentless_sequence?)?)* # BLOCK-END def parse_block_mapping_first_key(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_block_mapping_key() def parse_block_mapping_key(self): if self.check_token(KeyToken): token = self.get_token() if not self.check_token(KeyToken, ValueToken, BlockEndToken): self.states.append(self.parse_block_mapping_value) return self.parse_block_node_or_indentless_sequence() else: self.state = self.parse_block_mapping_value return self.process_empty_scalar(token.end_mark) if not self.check_token(BlockEndToken): token = self.peek_token() raise ParserError("while parsing a block mapping", self.marks[-1], "expected <block end>, but found %r" % token.id, token.start_mark) token = self.get_token() event = MappingEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event def parse_block_mapping_value(self): if self.check_token(ValueToken): token = self.get_token() if not self.check_token(KeyToken, ValueToken, BlockEndToken): self.states.append(self.parse_block_mapping_key) return self.parse_block_node_or_indentless_sequence() else: self.state = self.parse_block_mapping_key return self.process_empty_scalar(token.end_mark) else: self.state = self.parse_block_mapping_key token = self.peek_token() return self.process_empty_scalar(token.start_mark) # flow_sequence ::= FLOW-SEQUENCE-START # (flow_sequence_entry FLOW-ENTRY)* # flow_sequence_entry? # FLOW-SEQUENCE-END # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? # # Note that while production rules for both flow_sequence_entry and # flow_mapping_entry are equal, their interpretations are different. # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?` # generate an inline mapping (set syntax). def parse_flow_sequence_first_entry(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_flow_sequence_entry(first=True) def parse_flow_sequence_entry(self, first=False): if not self.check_token(FlowSequenceEndToken): if not first: if self.check_token(FlowEntryToken): self.get_token() else: token = self.peek_token() raise ParserError("while parsing a flow sequence", self.marks[-1], "expected ',' or ']', but got %r" % token.id, token.start_mark) if self.check_token(KeyToken): token = self.peek_token() event = MappingStartEvent(None, None, True, token.start_mark, token.end_mark, flow_style=True) self.state = self.parse_flow_sequence_entry_mapping_key return event elif not self.check_token(FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry) return self.parse_flow_node() token = self.get_token() event = SequenceEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event def parse_flow_sequence_entry_mapping_key(self): token = self.get_token() if not self.check_token(ValueToken, FlowEntryToken, FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry_mapping_value) return self.parse_flow_node() else: self.state = self.parse_flow_sequence_entry_mapping_value return self.process_empty_scalar(token.end_mark) def parse_flow_sequence_entry_mapping_value(self): if self.check_token(ValueToken): token = self.get_token() if not self.check_token(FlowEntryToken, FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry_mapping_end) return self.parse_flow_node() else: self.state = self.parse_flow_sequence_entry_mapping_end return self.process_empty_scalar(token.end_mark) else: self.state = self.parse_flow_sequence_entry_mapping_end token = self.peek_token() return self.process_empty_scalar(token.start_mark) def parse_flow_sequence_entry_mapping_end(self): self.state = self.parse_flow_sequence_entry token = self.peek_token() return MappingEndEvent(token.start_mark, token.start_mark) # flow_mapping ::= FLOW-MAPPING-START # (flow_mapping_entry FLOW-ENTRY)* # flow_mapping_entry? # FLOW-MAPPING-END # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? def parse_flow_mapping_first_key(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_flow_mapping_key(first=True) def parse_flow_mapping_key(self, first=False): if not self.check_token(FlowMappingEndToken): if not first: if self.check_token(FlowEntryToken): self.get_token() else: token = self.peek_token() raise ParserError("while parsing a flow mapping", self.marks[-1], "expected ',' or '}', but got %r" % token.id, token.start_mark) if self.check_token(KeyToken): token = self.get_token() if not self.check_token(ValueToken, FlowEntryToken, FlowMappingEndToken): self.states.append(self.parse_flow_mapping_value) return self.parse_flow_node() else: self.state = self.parse_flow_mapping_value return self.process_empty_scalar(token.end_mark) elif not self.check_token(FlowMappingEndToken): self.states.append(self.parse_flow_mapping_empty_value) return self.parse_flow_node() token = self.get_token() event = MappingEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event def parse_flow_mapping_value(self): if self.check_token(ValueToken): token = self.get_token() if not self.check_token(FlowEntryToken, FlowMappingEndToken): self.states.append(self.parse_flow_mapping_key) return self.parse_flow_node() else: self.state = self.parse_flow_mapping_key return self.process_empty_scalar(token.end_mark) else: self.state = self.parse_flow_mapping_key token = self.peek_token() return self.process_empty_scalar(token.start_mark) def parse_flow_mapping_empty_value(self): self.state = self.parse_flow_mapping_key return self.process_empty_scalar(self.peek_token().start_mark) def process_empty_scalar(self, mark): return ScalarEvent(None, None, (True, False), '', mark, mark)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/parser.py
parser.py
__all__ = ['Serializer', 'SerializerError'] from .error import YAMLError from .events import * from .nodes import * class SerializerError(YAMLError): pass class Serializer: ANCHOR_TEMPLATE = 'id%03d' def __init__(self, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): self.use_encoding = encoding self.use_explicit_start = explicit_start self.use_explicit_end = explicit_end self.use_version = version self.use_tags = tags self.serialized_nodes = {} self.anchors = {} self.last_anchor_id = 0 self.closed = None def open(self): if self.closed is None: self.emit(StreamStartEvent(encoding=self.use_encoding)) self.closed = False elif self.closed: raise SerializerError("serializer is closed") else: raise SerializerError("serializer is already opened") def close(self): if self.closed is None: raise SerializerError("serializer is not opened") elif not self.closed: self.emit(StreamEndEvent()) self.closed = True #def __del__(self): # self.close() def serialize(self, node): if self.closed is None: raise SerializerError("serializer is not opened") elif self.closed: raise SerializerError("serializer is closed") self.emit(DocumentStartEvent(explicit=self.use_explicit_start, version=self.use_version, tags=self.use_tags)) self.anchor_node(node) self.serialize_node(node, None, None) self.emit(DocumentEndEvent(explicit=self.use_explicit_end)) self.serialized_nodes = {} self.anchors = {} self.last_anchor_id = 0 def anchor_node(self, node): if node in self.anchors: if self.anchors[node] is None: self.anchors[node] = self.generate_anchor(node) else: self.anchors[node] = None if isinstance(node, SequenceNode): for item in node.value: self.anchor_node(item) elif isinstance(node, MappingNode): for key, value in node.value: self.anchor_node(key) self.anchor_node(value) def generate_anchor(self, node): self.last_anchor_id += 1 return self.ANCHOR_TEMPLATE % self.last_anchor_id def serialize_node(self, node, parent, index): alias = self.anchors[node] if node in self.serialized_nodes: self.emit(AliasEvent(alias)) else: self.serialized_nodes[node] = True self.descend_resolver(parent, index) if isinstance(node, ScalarNode): detected_tag = self.resolve(ScalarNode, node.value, (True, False)) default_tag = self.resolve(ScalarNode, node.value, (False, True)) implicit = (node.tag == detected_tag), (node.tag == default_tag) self.emit(ScalarEvent(alias, node.tag, implicit, node.value, style=node.style)) elif isinstance(node, SequenceNode): implicit = (node.tag == self.resolve(SequenceNode, node.value, True)) self.emit(SequenceStartEvent(alias, node.tag, implicit, flow_style=node.flow_style)) index = 0 for item in node.value: self.serialize_node(item, node, index) index += 1 self.emit(SequenceEndEvent()) elif isinstance(node, MappingNode): implicit = (node.tag == self.resolve(MappingNode, node.value, True)) self.emit(MappingStartEvent(alias, node.tag, implicit, flow_style=node.flow_style)) for key, value in node.value: self.serialize_node(key, node, None) self.serialize_node(value, node, key) self.emit(MappingEndEvent()) self.ascend_resolver()
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/serializer.py
serializer.py
__all__ = [ 'BaseConstructor', 'SafeConstructor', 'FullConstructor', 'UnsafeConstructor', 'Constructor', 'ConstructorError' ] from .error import * from .nodes import * import collections.abc, datetime, base64, binascii, re, sys, types class ConstructorError(MarkedYAMLError): pass class BaseConstructor: yaml_constructors = {} yaml_multi_constructors = {} def __init__(self): self.constructed_objects = {} self.recursive_objects = {} self.state_generators = [] self.deep_construct = False def check_data(self): # If there are more documents available? return self.check_node() def check_state_key(self, key): """Block special attributes/methods from being set in a newly created object, to prevent user-controlled methods from being called during deserialization""" if self.get_state_keys_blacklist_regexp().match(key): raise ConstructorError(None, None, "blacklisted key '%s' in instance state found" % (key,), None) def get_data(self): # Construct and return the next document. if self.check_node(): return self.construct_document(self.get_node()) def get_single_data(self): # Ensure that the stream contains a single document and construct it. node = self.get_single_node() if node is not None: return self.construct_document(node) return None def construct_document(self, node): data = self.construct_object(node) while self.state_generators: state_generators = self.state_generators self.state_generators = [] for generator in state_generators: for dummy in generator: pass self.constructed_objects = {} self.recursive_objects = {} self.deep_construct = False return data def construct_object(self, node, deep=False): if node in self.constructed_objects: return self.constructed_objects[node] if deep: old_deep = self.deep_construct self.deep_construct = True if node in self.recursive_objects: raise ConstructorError(None, None, "found unconstructable recursive node", node.start_mark) self.recursive_objects[node] = None constructor = None tag_suffix = None if node.tag in self.yaml_constructors: constructor = self.yaml_constructors[node.tag] else: for tag_prefix in self.yaml_multi_constructors: if tag_prefix is not None and node.tag.startswith(tag_prefix): tag_suffix = node.tag[len(tag_prefix):] constructor = self.yaml_multi_constructors[tag_prefix] break else: if None in self.yaml_multi_constructors: tag_suffix = node.tag constructor = self.yaml_multi_constructors[None] elif None in self.yaml_constructors: constructor = self.yaml_constructors[None] elif isinstance(node, ScalarNode): constructor = self.__class__.construct_scalar elif isinstance(node, SequenceNode): constructor = self.__class__.construct_sequence elif isinstance(node, MappingNode): constructor = self.__class__.construct_mapping if tag_suffix is None: data = constructor(self, node) else: data = constructor(self, tag_suffix, node) if isinstance(data, types.GeneratorType): generator = data data = next(generator) if self.deep_construct: for dummy in generator: pass else: self.state_generators.append(generator) self.constructed_objects[node] = data del self.recursive_objects[node] if deep: self.deep_construct = old_deep return data def construct_scalar(self, node): if not isinstance(node, ScalarNode): raise ConstructorError(None, None, "expected a scalar node, but found %s" % node.id, node.start_mark) return node.value def construct_sequence(self, node, deep=False): if not isinstance(node, SequenceNode): raise ConstructorError(None, None, "expected a sequence node, but found %s" % node.id, node.start_mark) return [self.construct_object(child, deep=deep) for child in node.value] def construct_mapping(self, node, deep=False): if not isinstance(node, MappingNode): raise ConstructorError(None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) mapping = {} for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) if not isinstance(key, collections.abc.Hashable): raise ConstructorError("while constructing a mapping", node.start_mark, "found unhashable key", key_node.start_mark) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping def construct_pairs(self, node, deep=False): if not isinstance(node, MappingNode): raise ConstructorError(None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) pairs = [] for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) value = self.construct_object(value_node, deep=deep) pairs.append((key, value)) return pairs @classmethod def add_constructor(cls, tag, constructor): if not 'yaml_constructors' in cls.__dict__: cls.yaml_constructors = cls.yaml_constructors.copy() cls.yaml_constructors[tag] = constructor @classmethod def add_multi_constructor(cls, tag_prefix, multi_constructor): if not 'yaml_multi_constructors' in cls.__dict__: cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy() cls.yaml_multi_constructors[tag_prefix] = multi_constructor class SafeConstructor(BaseConstructor): def construct_scalar(self, node): if isinstance(node, MappingNode): for key_node, value_node in node.value: if key_node.tag == 'tag:yaml.org,2002:value': return self.construct_scalar(value_node) return super().construct_scalar(node) def flatten_mapping(self, node): merge = [] index = 0 while index < len(node.value): key_node, value_node = node.value[index] if key_node.tag == 'tag:yaml.org,2002:merge': del node.value[index] if isinstance(value_node, MappingNode): self.flatten_mapping(value_node) merge.extend(value_node.value) elif isinstance(value_node, SequenceNode): submerge = [] for subnode in value_node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping for merging, but found %s" % subnode.id, subnode.start_mark) self.flatten_mapping(subnode) submerge.append(subnode.value) submerge.reverse() for value in submerge: merge.extend(value) else: raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping or list of mappings for merging, but found %s" % value_node.id, value_node.start_mark) elif key_node.tag == 'tag:yaml.org,2002:value': key_node.tag = 'tag:yaml.org,2002:str' index += 1 else: index += 1 if merge: node.value = merge + node.value def construct_mapping(self, node, deep=False): if isinstance(node, MappingNode): self.flatten_mapping(node) return super().construct_mapping(node, deep=deep) def construct_yaml_null(self, node): self.construct_scalar(node) return None bool_values = { 'yes': True, 'no': False, 'true': True, 'false': False, 'on': True, 'off': False, } def construct_yaml_bool(self, node): value = self.construct_scalar(node) return self.bool_values[value.lower()] def construct_yaml_int(self, node): value = self.construct_scalar(node) value = value.replace('_', '') sign = +1 if value[0] == '-': sign = -1 if value[0] in '+-': value = value[1:] if value == '0': return 0 elif value.startswith('0b'): return sign*int(value[2:], 2) elif value.startswith('0x'): return sign*int(value[2:], 16) elif value[0] == '0': return sign*int(value, 8) elif ':' in value: digits = [int(part) for part in value.split(':')] digits.reverse() base = 1 value = 0 for digit in digits: value += digit*base base *= 60 return sign*value else: return sign*int(value) inf_value = 1e300 while inf_value != inf_value*inf_value: inf_value *= inf_value nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99). def construct_yaml_float(self, node): value = self.construct_scalar(node) value = value.replace('_', '').lower() sign = +1 if value[0] == '-': sign = -1 if value[0] in '+-': value = value[1:] if value == '.inf': return sign*self.inf_value elif value == '.nan': return self.nan_value elif ':' in value: digits = [float(part) for part in value.split(':')] digits.reverse() base = 1 value = 0.0 for digit in digits: value += digit*base base *= 60 return sign*value else: return sign*float(value) def construct_yaml_binary(self, node): try: value = self.construct_scalar(node).encode('ascii') except UnicodeEncodeError as exc: raise ConstructorError(None, None, "failed to convert base64 data into ascii: %s" % exc, node.start_mark) try: if hasattr(base64, 'decodebytes'): return base64.decodebytes(value) else: return base64.decodestring(value) except binascii.Error as exc: raise ConstructorError(None, None, "failed to decode base64 data: %s" % exc, node.start_mark) timestamp_regexp = re.compile( r'''^(?P<year>[0-9][0-9][0-9][0-9]) -(?P<month>[0-9][0-9]?) -(?P<day>[0-9][0-9]?) (?:(?:[Tt]|[ \t]+) (?P<hour>[0-9][0-9]?) :(?P<minute>[0-9][0-9]) :(?P<second>[0-9][0-9]) (?:\.(?P<fraction>[0-9]*))? (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?) (?::(?P<tz_minute>[0-9][0-9]))?))?)?$''', re.X) def construct_yaml_timestamp(self, node): value = self.construct_scalar(node) match = self.timestamp_regexp.match(node.value) values = match.groupdict() year = int(values['year']) month = int(values['month']) day = int(values['day']) if not values['hour']: return datetime.date(year, month, day) hour = int(values['hour']) minute = int(values['minute']) second = int(values['second']) fraction = 0 tzinfo = None if values['fraction']: fraction = values['fraction'][:6] while len(fraction) < 6: fraction += '0' fraction = int(fraction) if values['tz_sign']: tz_hour = int(values['tz_hour']) tz_minute = int(values['tz_minute'] or 0) delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute) if values['tz_sign'] == '-': delta = -delta tzinfo = datetime.timezone(delta) elif values['tz']: tzinfo = datetime.timezone.utc return datetime.datetime(year, month, day, hour, minute, second, fraction, tzinfo=tzinfo) def construct_yaml_omap(self, node): # Note: we do not check for duplicate keys, because it's too # CPU-expensive. omap = [] yield omap if not isinstance(node, SequenceNode): raise ConstructorError("while constructing an ordered map", node.start_mark, "expected a sequence, but found %s" % node.id, node.start_mark) for subnode in node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing an ordered map", node.start_mark, "expected a mapping of length 1, but found %s" % subnode.id, subnode.start_mark) if len(subnode.value) != 1: raise ConstructorError("while constructing an ordered map", node.start_mark, "expected a single mapping item, but found %d items" % len(subnode.value), subnode.start_mark) key_node, value_node = subnode.value[0] key = self.construct_object(key_node) value = self.construct_object(value_node) omap.append((key, value)) def construct_yaml_pairs(self, node): # Note: the same code as `construct_yaml_omap`. pairs = [] yield pairs if not isinstance(node, SequenceNode): raise ConstructorError("while constructing pairs", node.start_mark, "expected a sequence, but found %s" % node.id, node.start_mark) for subnode in node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing pairs", node.start_mark, "expected a mapping of length 1, but found %s" % subnode.id, subnode.start_mark) if len(subnode.value) != 1: raise ConstructorError("while constructing pairs", node.start_mark, "expected a single mapping item, but found %d items" % len(subnode.value), subnode.start_mark) key_node, value_node = subnode.value[0] key = self.construct_object(key_node) value = self.construct_object(value_node) pairs.append((key, value)) def construct_yaml_set(self, node): data = set() yield data value = self.construct_mapping(node) data.update(value) def construct_yaml_str(self, node): return self.construct_scalar(node) def construct_yaml_seq(self, node): data = [] yield data data.extend(self.construct_sequence(node)) def construct_yaml_map(self, node): data = {} yield data value = self.construct_mapping(node) data.update(value) def construct_yaml_object(self, node, cls): data = cls.__new__(cls) yield data if hasattr(data, '__setstate__'): state = self.construct_mapping(node, deep=True) data.__setstate__(state) else: state = self.construct_mapping(node) data.__dict__.update(state) def construct_undefined(self, node): raise ConstructorError(None, None, "could not determine a constructor for the tag %r" % node.tag, node.start_mark) SafeConstructor.add_constructor( 'tag:yaml.org,2002:null', SafeConstructor.construct_yaml_null) SafeConstructor.add_constructor( 'tag:yaml.org,2002:bool', SafeConstructor.construct_yaml_bool) SafeConstructor.add_constructor( 'tag:yaml.org,2002:int', SafeConstructor.construct_yaml_int) SafeConstructor.add_constructor( 'tag:yaml.org,2002:float', SafeConstructor.construct_yaml_float) SafeConstructor.add_constructor( 'tag:yaml.org,2002:binary', SafeConstructor.construct_yaml_binary) SafeConstructor.add_constructor( 'tag:yaml.org,2002:timestamp', SafeConstructor.construct_yaml_timestamp) SafeConstructor.add_constructor( 'tag:yaml.org,2002:omap', SafeConstructor.construct_yaml_omap) SafeConstructor.add_constructor( 'tag:yaml.org,2002:pairs', SafeConstructor.construct_yaml_pairs) SafeConstructor.add_constructor( 'tag:yaml.org,2002:set', SafeConstructor.construct_yaml_set) SafeConstructor.add_constructor( 'tag:yaml.org,2002:str', SafeConstructor.construct_yaml_str) SafeConstructor.add_constructor( 'tag:yaml.org,2002:seq', SafeConstructor.construct_yaml_seq) SafeConstructor.add_constructor( 'tag:yaml.org,2002:map', SafeConstructor.construct_yaml_map) SafeConstructor.add_constructor(None, SafeConstructor.construct_undefined) class FullConstructor(SafeConstructor): # 'extend' is blacklisted because it is used by # construct_python_object_apply to add `listitems` to a newly generate # python instance def get_state_keys_blacklist(self): return ['^extend$', '^__.*__$'] def get_state_keys_blacklist_regexp(self): if not hasattr(self, 'state_keys_blacklist_regexp'): self.state_keys_blacklist_regexp = re.compile('(' + '|'.join(self.get_state_keys_blacklist()) + ')') return self.state_keys_blacklist_regexp def construct_python_str(self, node): return self.construct_scalar(node) def construct_python_unicode(self, node): return self.construct_scalar(node) def construct_python_bytes(self, node): try: value = self.construct_scalar(node).encode('ascii') except UnicodeEncodeError as exc: raise ConstructorError(None, None, "failed to convert base64 data into ascii: %s" % exc, node.start_mark) try: if hasattr(base64, 'decodebytes'): return base64.decodebytes(value) else: return base64.decodestring(value) except binascii.Error as exc: raise ConstructorError(None, None, "failed to decode base64 data: %s" % exc, node.start_mark) def construct_python_long(self, node): return self.construct_yaml_int(node) def construct_python_complex(self, node): return complex(self.construct_scalar(node)) def construct_python_tuple(self, node): return tuple(self.construct_sequence(node)) def find_python_module(self, name, mark, unsafe=False): if not name: raise ConstructorError("while constructing a Python module", mark, "expected non-empty name appended to the tag", mark) if unsafe: try: __import__(name) except ImportError as exc: raise ConstructorError("while constructing a Python module", mark, "cannot find module %r (%s)" % (name, exc), mark) if name not in sys.modules: raise ConstructorError("while constructing a Python module", mark, "module %r is not imported" % name, mark) return sys.modules[name] def find_python_name(self, name, mark, unsafe=False): if not name: raise ConstructorError("while constructing a Python object", mark, "expected non-empty name appended to the tag", mark) if '.' in name: module_name, object_name = name.rsplit('.', 1) else: module_name = 'builtins' object_name = name if unsafe: try: __import__(module_name) except ImportError as exc: raise ConstructorError("while constructing a Python object", mark, "cannot find module %r (%s)" % (module_name, exc), mark) if module_name not in sys.modules: raise ConstructorError("while constructing a Python object", mark, "module %r is not imported" % module_name, mark) module = sys.modules[module_name] if not hasattr(module, object_name): raise ConstructorError("while constructing a Python object", mark, "cannot find %r in the module %r" % (object_name, module.__name__), mark) return getattr(module, object_name) def construct_python_name(self, suffix, node): value = self.construct_scalar(node) if value: raise ConstructorError("while constructing a Python name", node.start_mark, "expected the empty value, but found %r" % value, node.start_mark) return self.find_python_name(suffix, node.start_mark) def construct_python_module(self, suffix, node): value = self.construct_scalar(node) if value: raise ConstructorError("while constructing a Python module", node.start_mark, "expected the empty value, but found %r" % value, node.start_mark) return self.find_python_module(suffix, node.start_mark) def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False, unsafe=False): if not args: args = [] if not kwds: kwds = {} cls = self.find_python_name(suffix, node.start_mark) if not (unsafe or isinstance(cls, type)): raise ConstructorError("while constructing a Python instance", node.start_mark, "expected a class, but found %r" % type(cls), node.start_mark) if newobj and isinstance(cls, type): return cls.__new__(cls, *args, **kwds) else: return cls(*args, **kwds) def set_python_instance_state(self, instance, state, unsafe=False): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else: slotstate = {} if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if hasattr(instance, '__dict__'): if not unsafe and state: for key in state.keys(): self.check_state_key(key) instance.__dict__.update(state) elif state: slotstate.update(state) for key, value in slotstate.items(): if not unsafe: self.check_state_key(key) setattr(instance, key, value) def construct_python_object(self, suffix, node): # Format: # !!python/object:module.name { ... state ... } instance = self.make_python_instance(suffix, node, newobj=True) yield instance deep = hasattr(instance, '__setstate__') state = self.construct_mapping(node, deep=deep) self.set_python_instance_state(instance, state) def construct_python_object_apply(self, suffix, node, newobj=False): # Format: # !!python/object/apply # (or !!python/object/new) # args: [ ... arguments ... ] # kwds: { ... keywords ... } # state: ... state ... # listitems: [ ... listitems ... ] # dictitems: { ... dictitems ... } # or short format: # !!python/object/apply [ ... arguments ... ] # The difference between !!python/object/apply and !!python/object/new # is how an object is created, check make_python_instance for details. if isinstance(node, SequenceNode): args = self.construct_sequence(node, deep=True) kwds = {} state = {} listitems = [] dictitems = {} else: value = self.construct_mapping(node, deep=True) args = value.get('args', []) kwds = value.get('kwds', {}) state = value.get('state', {}) listitems = value.get('listitems', []) dictitems = value.get('dictitems', {}) instance = self.make_python_instance(suffix, node, args, kwds, newobj) if state: self.set_python_instance_state(instance, state) if listitems: instance.extend(listitems) if dictitems: for key in dictitems: instance[key] = dictitems[key] return instance def construct_python_object_new(self, suffix, node): return self.construct_python_object_apply(suffix, node, newobj=True) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/none', FullConstructor.construct_yaml_null) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/bool', FullConstructor.construct_yaml_bool) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/str', FullConstructor.construct_python_str) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/unicode', FullConstructor.construct_python_unicode) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/bytes', FullConstructor.construct_python_bytes) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/int', FullConstructor.construct_yaml_int) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/long', FullConstructor.construct_python_long) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/float', FullConstructor.construct_yaml_float) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/complex', FullConstructor.construct_python_complex) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/list', FullConstructor.construct_yaml_seq) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/tuple', FullConstructor.construct_python_tuple) FullConstructor.add_constructor( 'tag:yaml.org,2002:python/dict', FullConstructor.construct_yaml_map) FullConstructor.add_multi_constructor( 'tag:yaml.org,2002:python/name:', FullConstructor.construct_python_name) class UnsafeConstructor(FullConstructor): def find_python_module(self, name, mark): return super(UnsafeConstructor, self).find_python_module(name, mark, unsafe=True) def find_python_name(self, name, mark): return super(UnsafeConstructor, self).find_python_name(name, mark, unsafe=True) def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False): return super(UnsafeConstructor, self).make_python_instance( suffix, node, args, kwds, newobj, unsafe=True) def set_python_instance_state(self, instance, state): return super(UnsafeConstructor, self).set_python_instance_state( instance, state, unsafe=True) UnsafeConstructor.add_multi_constructor( 'tag:yaml.org,2002:python/module:', UnsafeConstructor.construct_python_module) UnsafeConstructor.add_multi_constructor( 'tag:yaml.org,2002:python/object:', UnsafeConstructor.construct_python_object) UnsafeConstructor.add_multi_constructor( 'tag:yaml.org,2002:python/object/new:', UnsafeConstructor.construct_python_object_new) UnsafeConstructor.add_multi_constructor( 'tag:yaml.org,2002:python/object/apply:', UnsafeConstructor.construct_python_object_apply) # Constructor is same as UnsafeConstructor. Need to leave this in place in case # people have extended it directly. class Constructor(UnsafeConstructor): pass
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/constructor.py
constructor.py
from .error import * from .tokens import * from .events import * from .nodes import * from .loader import * from .dumper import * __version__ = '6.0' try: from .cyaml import * __with_libyaml__ = True except ImportError: __with_libyaml__ = False import io #------------------------------------------------------------------------------ # XXX "Warnings control" is now deprecated. Leaving in the API function to not # break code that uses it. #------------------------------------------------------------------------------ def warnings(settings=None): if settings is None: return {} #------------------------------------------------------------------------------ def scan(stream, Loader=Loader): """ Scan a YAML stream and produce scanning tokens. """ loader = Loader(stream) try: while loader.check_token(): yield loader.get_token() finally: loader.dispose() def parse(stream, Loader=Loader): """ Parse a YAML stream and produce parsing events. """ loader = Loader(stream) try: while loader.check_event(): yield loader.get_event() finally: loader.dispose() def compose(stream, Loader=Loader): """ Parse the first YAML document in a stream and produce the corresponding representation tree. """ loader = Loader(stream) try: return loader.get_single_node() finally: loader.dispose() def compose_all(stream, Loader=Loader): """ Parse all YAML documents in a stream and produce corresponding representation trees. """ loader = Loader(stream) try: while loader.check_node(): yield loader.get_node() finally: loader.dispose() def load(stream, Loader): """ Parse the first YAML document in a stream and produce the corresponding Python object. """ loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose() def load_all(stream, Loader): """ Parse all YAML documents in a stream and produce corresponding Python objects. """ loader = Loader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose() def full_load(stream): """ Parse the first YAML document in a stream and produce the corresponding Python object. Resolve all tags except those known to be unsafe on untrusted input. """ return load(stream, FullLoader) def full_load_all(stream): """ Parse all YAML documents in a stream and produce corresponding Python objects. Resolve all tags except those known to be unsafe on untrusted input. """ return load_all(stream, FullLoader) def safe_load(stream): """ Parse the first YAML document in a stream and produce the corresponding Python object. Resolve only basic YAML tags. This is known to be safe for untrusted input. """ return load(stream, SafeLoader) def safe_load_all(stream): """ Parse all YAML documents in a stream and produce corresponding Python objects. Resolve only basic YAML tags. This is known to be safe for untrusted input. """ return load_all(stream, SafeLoader) def unsafe_load(stream): """ Parse the first YAML document in a stream and produce the corresponding Python object. Resolve all tags, even those known to be unsafe on untrusted input. """ return load(stream, UnsafeLoader) def unsafe_load_all(stream): """ Parse all YAML documents in a stream and produce corresponding Python objects. Resolve all tags, even those known to be unsafe on untrusted input. """ return load_all(stream, UnsafeLoader) def emit(events, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None): """ Emit YAML parsing events into a stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: stream = io.StringIO() getvalue = stream.getvalue dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break) try: for event in events: dumper.emit(event) finally: dumper.dispose() if getvalue: return getvalue() def serialize_all(nodes, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): """ Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: if encoding is None: stream = io.StringIO() else: stream = io.BytesIO() getvalue = stream.getvalue dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, encoding=encoding, version=version, tags=tags, explicit_start=explicit_start, explicit_end=explicit_end) try: dumper.open() for node in nodes: dumper.serialize(node) dumper.close() finally: dumper.dispose() if getvalue: return getvalue() def serialize(node, stream=None, Dumper=Dumper, **kwds): """ Serialize a representation tree into a YAML stream. If stream is None, return the produced string instead. """ return serialize_all([node], stream, Dumper=Dumper, **kwds) def dump_all(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True): """ Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: if encoding is None: stream = io.StringIO() else: stream = io.BytesIO() getvalue = stream.getvalue dumper = Dumper(stream, default_style=default_style, default_flow_style=default_flow_style, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, encoding=encoding, version=version, tags=tags, explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys) try: dumper.open() for data in documents: dumper.represent(data) dumper.close() finally: dumper.dispose() if getvalue: return getvalue() def dump(data, stream=None, Dumper=Dumper, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=Dumper, **kwds) def safe_dump_all(documents, stream=None, **kwds): """ Serialize a sequence of Python objects into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead. """ return dump_all(documents, stream, Dumper=SafeDumper, **kwds) def safe_dump(data, stream=None, **kwds): """ Serialize a Python object into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=SafeDumper, **kwds) def add_implicit_resolver(tag, regexp, first=None, Loader=None, Dumper=Dumper): """ Add an implicit scalar detector. If an implicit scalar value matches the given regexp, the corresponding tag is assigned to the scalar. first is a sequence of possible initial characters or None. """ if Loader is None: loader.Loader.add_implicit_resolver(tag, regexp, first) loader.FullLoader.add_implicit_resolver(tag, regexp, first) loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first) else: Loader.add_implicit_resolver(tag, regexp, first) Dumper.add_implicit_resolver(tag, regexp, first) def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper): """ Add a path based resolver for the given tag. A path is a list of keys that forms a path to a node in the representation tree. Keys can be string values, integers, or None. """ if Loader is None: loader.Loader.add_path_resolver(tag, path, kind) loader.FullLoader.add_path_resolver(tag, path, kind) loader.UnsafeLoader.add_path_resolver(tag, path, kind) else: Loader.add_path_resolver(tag, path, kind) Dumper.add_path_resolver(tag, path, kind) def add_constructor(tag, constructor, Loader=None): """ Add a constructor for the given tag. Constructor is a function that accepts a Loader instance and a node object and produces the corresponding Python object. """ if Loader is None: loader.Loader.add_constructor(tag, constructor) loader.FullLoader.add_constructor(tag, constructor) loader.UnsafeLoader.add_constructor(tag, constructor) else: Loader.add_constructor(tag, constructor) def add_multi_constructor(tag_prefix, multi_constructor, Loader=None): """ Add a multi-constructor for the given tag prefix. Multi-constructor is called for a node if its tag starts with tag_prefix. Multi-constructor accepts a Loader instance, a tag suffix, and a node object and produces the corresponding Python object. """ if Loader is None: loader.Loader.add_multi_constructor(tag_prefix, multi_constructor) loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor) loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor) else: Loader.add_multi_constructor(tag_prefix, multi_constructor) def add_representer(data_type, representer, Dumper=Dumper): """ Add a representer for the given type. Representer is a function accepting a Dumper instance and an instance of the given data type and producing the corresponding representation node. """ Dumper.add_representer(data_type, representer) def add_multi_representer(data_type, multi_representer, Dumper=Dumper): """ Add a representer for the given type. Multi-representer is a function accepting a Dumper instance and an instance of the given data type or subtype and producing the corresponding representation node. """ Dumper.add_multi_representer(data_type, multi_representer) class YAMLObjectMetaclass(type): """ The metaclass for YAMLObject. """ def __init__(cls, name, bases, kwds): super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds) if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None: if isinstance(cls.yaml_loader, list): for loader in cls.yaml_loader: loader.add_constructor(cls.yaml_tag, cls.from_yaml) else: cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml) cls.yaml_dumper.add_representer(cls, cls.to_yaml) class YAMLObject(metaclass=YAMLObjectMetaclass): """ An object that can dump itself to a YAML stream and load itself from a YAML stream. """ __slots__ = () # no direct instantiation, so allow immutable subclasses yaml_loader = [Loader, FullLoader, UnsafeLoader] yaml_dumper = Dumper yaml_tag = None yaml_flow_style = None @classmethod def from_yaml(cls, loader, node): """ Convert a representation node to a Python object. """ return loader.construct_yaml_object(node, cls) @classmethod def to_yaml(cls, dumper, data): """ Convert a Python object to a representation node. """ return dumper.represent_yaml_object(cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/__init__.py
__init__.py
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper'] from .emitter import * from .serializer import * from .representer import * from .resolver import * class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): def __init__(self, stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True): Emitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break) Serializer.__init__(self, encoding=encoding, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) Representer.__init__(self, default_style=default_style, default_flow_style=default_flow_style, sort_keys=sort_keys) Resolver.__init__(self) class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver): def __init__(self, stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True): Emitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break) Serializer.__init__(self, encoding=encoding, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) SafeRepresenter.__init__(self, default_style=default_style, default_flow_style=default_flow_style, sort_keys=sort_keys) Resolver.__init__(self) class Dumper(Emitter, Serializer, Representer, Resolver): def __init__(self, stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True): Emitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break) Serializer.__init__(self, encoding=encoding, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) Representer.__init__(self, default_style=default_style, default_flow_style=default_flow_style, sort_keys=sort_keys) Resolver.__init__(self)
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/dumper.py
dumper.py
__all__ = ['Composer', 'ComposerError'] from .error import MarkedYAMLError from .events import * from .nodes import * class ComposerError(MarkedYAMLError): pass class Composer: def __init__(self): self.anchors = {} def check_node(self): # Drop the STREAM-START event. if self.check_event(StreamStartEvent): self.get_event() # If there are more documents available? return not self.check_event(StreamEndEvent) def get_node(self): # Get the root node of the next document. if not self.check_event(StreamEndEvent): return self.compose_document() def get_single_node(self): # Drop the STREAM-START event. self.get_event() # Compose a document if the stream is not empty. document = None if not self.check_event(StreamEndEvent): document = self.compose_document() # Ensure that the stream contains no more documents. if not self.check_event(StreamEndEvent): event = self.get_event() raise ComposerError("expected a single document in the stream", document.start_mark, "but found another document", event.start_mark) # Drop the STREAM-END event. self.get_event() return document def compose_document(self): # Drop the DOCUMENT-START event. self.get_event() # Compose the root node. node = self.compose_node(None, None) # Drop the DOCUMENT-END event. self.get_event() self.anchors = {} return node def compose_node(self, parent, index): if self.check_event(AliasEvent): event = self.get_event() anchor = event.anchor if anchor not in self.anchors: raise ComposerError(None, None, "found undefined alias %r" % anchor, event.start_mark) return self.anchors[anchor] event = self.peek_event() anchor = event.anchor if anchor is not None: if anchor in self.anchors: raise ComposerError("found duplicate anchor %r; first occurrence" % anchor, self.anchors[anchor].start_mark, "second occurrence", event.start_mark) self.descend_resolver(parent, index) if self.check_event(ScalarEvent): node = self.compose_scalar_node(anchor) elif self.check_event(SequenceStartEvent): node = self.compose_sequence_node(anchor) elif self.check_event(MappingStartEvent): node = self.compose_mapping_node(anchor) self.ascend_resolver() return node def compose_scalar_node(self, anchor): event = self.get_event() tag = event.tag if tag is None or tag == '!': tag = self.resolve(ScalarNode, event.value, event.implicit) node = ScalarNode(tag, event.value, event.start_mark, event.end_mark, style=event.style) if anchor is not None: self.anchors[anchor] = node return node def compose_sequence_node(self, anchor): start_event = self.get_event() tag = start_event.tag if tag is None or tag == '!': tag = self.resolve(SequenceNode, None, start_event.implicit) node = SequenceNode(tag, [], start_event.start_mark, None, flow_style=start_event.flow_style) if anchor is not None: self.anchors[anchor] = node index = 0 while not self.check_event(SequenceEndEvent): node.value.append(self.compose_node(node, index)) index += 1 end_event = self.get_event() node.end_mark = end_event.end_mark return node def compose_mapping_node(self, anchor): start_event = self.get_event() tag = start_event.tag if tag is None or tag == '!': tag = self.resolve(MappingNode, None, start_event.implicit) node = MappingNode(tag, [], start_event.start_mark, None, flow_style=start_event.flow_style) if anchor is not None: self.anchors[anchor] = node while not self.check_event(MappingEndEvent): #key_event = self.peek_event() item_key = self.compose_node(node, None) #if item_key in node.value: # raise ComposerError("while composing a mapping", start_event.start_mark, # "found duplicate key", key_event.start_mark) item_value = self.compose_node(node, item_key) #node.value[item_key] = item_value node.value.append((item_key, item_value)) end_event = self.get_event() node.end_mark = end_event.end_mark return node
zdppy-yaml
/zdppy_yaml-0.1.1-py3-none-any.whl/zdppy_yaml/libs/yaml/composer.py
composer.py
import json import boto3 import atexit import logging from functools import partial from datadog import DogStatsd from zocdoc.canoe.timehelp import to_utc logger = logging.getLogger(__name__) def to_lambda_metric_format(metric_type, timestamp, metric_name, value=1, tags=None): time_str = (to_utc(timestamp) if not hasattr(timestamp, 'strftime') else timestamp).strftime('%s') return 'MONITORING|{epoch}|{value}|{metric_type}|{metric_name}|#{tags}'.format( epoch=time_str, value=value, metric_type=metric_type, metric_name=metric_name, tags=','.join(tags or []) ) def cleanup_client(client): try: client.flush() except Exception as e: logger.info('{} failed on atexit cleanup {}'.format(type(client), e)) class MetricLambdaClient(object): @staticmethod def get_default_lambda_client(): return boto3.client('lambda') @staticmethod def create(lambda_name=None, lambda_client=None): return MetricLambdaClient( lambda_name=lambda_name, lambda_client=(lambda_client or MetricLambdaClient.get_default_lambda_client()) ) def __init__(self, lambda_client=None, lambda_name=None): self.lambda_client = lambda_client self.lambda_name = lambda_name self._staged_messages = [] atexit.register(cleanup_client, self) def _send_message(self, message): return self.lambda_client.invoke( FunctionName=self.lambda_name, InvocationType='Event', Payload=json.dumps(dict(payload=message)) ) def _stage_message(self, message): self._staged_messages.append(message) def flush(self): if self._staged_messages: self._send_message(self._staged_messages) self._staged_messages = [] def send_metric(self, *args, **kwargs): self._send_message(to_lambda_metric_format(*args, **kwargs)) def stage_metric(self, *args, **kwargs): self._stage_message(to_lambda_metric_format(*args, **kwargs)) class MockDogStatsd(object): def __init__(self, **kwargs): logger.debug('Create mock DogStatsd {}'.format(str(kwargs))) def __getattr__(self, item): def wrapper(*args, **kwargs): logger.debug('Calling {} with args {} and kwargs {}'.format(item, str(args), str(kwargs))) return wrapper def get_datadog_client(app_config): if app_config.deployment_environment == 'dev': return MockDogStatsd() else: return DogStatsd( host=app_config.datadog_host, port=app_config.datadog_port, namespace=app_config.datadog_namespace, use_ms=True )
zdpy
/zdpy-0.1.0.tar.gz/zdpy-0.1.0/src/zd/test/metrics/__init__.py
__init__.py
import uuid import math import json import boto3 import logging from itertools import chain from collections import namedtuple from zocdoc.canoe.tools import list_to_batches logger = logging.getLogger(__name__) class SqsMessageWrapper(object): def __init__(self, message_object): self.message_object = message_object self.__body = None @property def body(self): if self.__body is None: try: self.__body = json.loads(self.message_object.body) except: self.__body = self.message_object.body return self.__body def __getattr__(self, item): return getattr(self.message_object, item) class SqsMessageEventRecord(SqsMessageWrapper): def __init__(self, event_record, *args, **kwargs): super(SqsMessageEventRecord, self).__init__(*args, **kwargs) self.event_record = event_record def queue_approximate_number_of_messages(queue_resource): return int(queue_resource.attributes.get('ApproximateNumberOfMessages') or '0') def query_sqs_messages(queue, max_message_count=10): BOTO3_MAXIMUM_INPUT = 10 # boto3 maximum input min_number_of_tries = int(math.ceil(max_message_count / 10.0)) try_count, new_msgs = 0, [] while ( len(new_msgs) < max_message_count and try_count < min_number_of_tries and queue_approximate_number_of_messages(queue)): try: try_count += 1 num_of_messages_get = min(BOTO3_MAXIMUM_INPUT, max_message_count, max_message_count - len(new_msgs)) msgs = queue.receive_messages(MaxNumberOfMessages=num_of_messages_get) new_msgs.extend(SqsMessageWrapper(m) for m in msgs) except Exception as e: logger.info('Error on pinging queue - ' + str(e)) logger.error(e) print(e) return new_msgs def to_sqs_delete_entries(messages): return [{'Id': str(i), 'ReceiptHandle': msg.receipt_handle} for i, msg in enumerate(messages)] def delete_sqs_messages(queue, entries): """ can only delete 10 per batch. that sucks. i want more. :param queue: the boto3 queue resource :param entries: [{'Id': 'str id', 'ReceiptHandle': 'str'}, ...] """ processed, response = 0, {'Successful': [], 'Failed': []} while processed < len(entries): try: next_batch = entries[processed:min((processed+10), len(entries))] next_resp = queue.delete_messages(Entries=next_batch) response['Successful'].extend(next_resp.get('Successful')) response['Failed'].extend(next_resp.get('Failed', [])) processed += len(next_batch) except Exception as e: logger.info( 'Message: Failure on SQS.Queue batch message delete - Error: {err} - QueueUrl: {queue_url}'.format( err=str(type(e)) + str(e), queue_url=queue.url ) ) raise e return response def send_sqs_messages(queue, messages, is_fifo_queue=False): """ can only send 10 per batch. that sucks. i want more. :param queue: the boto3 queue resource :param entries: list of dictionaries each of the form { 'message_body': (optional) json serializable blob, default = whole blob 'id': (optional) str, default = str(int corresponding to input list index) 'message_deduplication_id': (optional) str, default = guid 'message_group_id': (optional) str, default = '1' so all messages in same group } """ BOTO3_MAXIMUM_INPUT = 10 def to_message_parameters(id, message_blob, is_fifo): input_params = dict( Id=message_blob.get('id') or id, MessageBody=json.dumps(message_blob.get('message_body') or message_blob) ) if is_fifo: input_params.update( MessageDeduplicationId=message_blob.get('message_deduplication_id') or str(uuid.uuid4()), MessageGroupId=message_blob.get('message_group_id') or '1', ) return input_params response = dict(Successful=[], Failed=[]) try: for batch_number, message_batch in enumerate(list_to_batches(messages, BOTO3_MAXIMUM_INPUT)): as_valid_input_params = [ to_message_parameters(str(batch_number*BOTO3_MAXIMUM_INPUT + i), message, is_fifo_queue) for i, message in enumerate(message_batch) ] batch_response = queue.send_messages(Entries=as_valid_input_params) response['Successful'].extend(batch_response.get('Successful') or []) response['Failed'].extend(batch_response.get('Failed') or []) except Exception as e: logger.info( 'Message: Failure on SQS.Queue batch send message - Error: {err} - QueueUrl: {queue_url}'.format( err=str(type(e)) + str(e), queue_url=queue.url ) ) raise e return response _object_info_fields = [ 'bucket_name', 'bucket_arn', 'object_key', 'object_eTag', 'object_sequencer', 'object_size', 'region', 'event_name', 'event_version', 'event_time' ] S3EventObjectInfo = namedtuple('S3EventObjectInfo', _object_info_fields) def sqs_s3_messages(sqs_message): def to_s3_event_summary(record): # full message format https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html s3_bucket = record.get('s3').get('bucket') s3_object = record.get('s3').get('object') return S3EventObjectInfo( s3_bucket.get('name'), s3_bucket.get('arn'), s3_object.get('key'), s3_object.get('eTag'), s3_object.get('sequencer'), s3_object.get('size'), record.get('awsRegion'), record.get('eventName'), record.get('eventVersion'), record.get('eventTime') ) filtered_fields_messages = [SqsMessageEventRecord(to_s3_event_summary(rec), sqs_message) for rec in json.loads(sqs_message.body['Message']).get('Records', []) if 's3' in rec] return filtered_fields_messages def latest_s3_message_by_key(sqs_s3_msgs): if not sqs_s3_msgs: return [] kv = {(msg.event_record.object_key, msg.event_record.object_sequencer): msg for msg in sqs_s3_msgs} list_agg = {u_k: [] for u_k in set(k for k, _ in kv.keys())} for k, v in kv.keys(): list_agg[k].append(v) latest = [(k, sorted(v)[-1]) for k, v in list_agg.items()] return [kv[latest_kv] for latest_kv in latest] class SqsQueue(object): def __init__(self, queue_name, message_transformer=None, sqs_resource=None): self.queue_name = queue_name self.sqs_resource = sqs_resource or boto3.resource('sqs') self.queue = None self.message_transformer = message_transformer def get_queue(self): self.queue = self.sqs_resource.get_queue_by_name(QueueName=self.queue_name) return self def approximate_number_of_messages(self): return queue_approximate_number_of_messages(self.queue) def fifo_queue(self): return (self.queue.attributes.get('FifoQueue') or '').lower() == 'true' def has_messages(self): return self.approximate_number_of_messages() > 0 def receive_messages(self, **kwargs): update_func = self.message_transformer if self.message_transformer else (lambda m: [m]) return list(chain(*[update_func(msg) for msg in query_sqs_messages(queue=self.queue, **kwargs)])) def delete_messages(self, messages): try: resp = delete_sqs_messages(self.queue, entries=to_sqs_delete_entries(messages)) successful = resp.get('Successful', []) success_ct = len(successful) log_msg = 'Message: Removed messages from queue - DeletedMessageCount: {} - DeletedAllMessages: {}' logger.info(log_msg.format(success_ct, len(messages) == success_ct)) failed = resp.get('Failed', []) if failed: log_msg = 'Message: Subset of SQS.Queue batch delete calls failed - FailedDeletes: {}' logger.info(log_msg.format([dict(messages[fail['Id']], **fail) for fail in failed])) return resp except: pass def send_messages(self, messages): return send_sqs_messages(self.queue, messages, self.fifo_queue())
zdpy
/zdpy-0.1.0.tar.gz/zdpy-0.1.0/src/zd/test/aws/sqs.py
sqs.py
import uuid import math import json import boto3 import logging from itertools import chain from collections import namedtuple from zocdoc.canoe.tools import list_to_batches logger = logging.getLogger(__name__) class SqsMessageWrapper(object): def __init__(self, message_object): self.message_object = message_object self.__body = None @property def body(self): if self.__body is None: try: self.__body = json.loads(self.message_object.body) except: self.__body = self.message_object.body return self.__body def __getattr__(self, item): return getattr(self.message_object, item) class SqsMessageEventRecord(SqsMessageWrapper): def __init__(self, event_record, *args, **kwargs): super(SqsMessageEventRecord, self).__init__(*args, **kwargs) self.event_record = event_record def queue_approximate_number_of_messages(queue_resource): return int(queue_resource.attributes.get('ApproximateNumberOfMessages') or '0') def query_sqs_messages(queue, max_message_count=10): BOTO3_MAXIMUM_INPUT = 10 # boto3 maximum input min_number_of_tries = int(math.ceil(max_message_count / 10.0)) try_count, new_msgs = 0, [] while ( len(new_msgs) < max_message_count and try_count < min_number_of_tries and queue_approximate_number_of_messages(queue)): try: try_count += 1 num_of_messages_get = min(BOTO3_MAXIMUM_INPUT, max_message_count, max_message_count - len(new_msgs)) msgs = queue.receive_messages(MaxNumberOfMessages=num_of_messages_get) new_msgs.extend(SqsMessageWrapper(m) for m in msgs) except Exception as e: logger.info('Error on pinging queue - ' + str(e)) logger.error(e) print(e) return new_msgs def to_sqs_delete_entries(messages): return [{'Id': str(i), 'ReceiptHandle': msg.receipt_handle} for i, msg in enumerate(messages)] def delete_sqs_messages(queue, entries): """ can only delete 10 per batch. that sucks. i want more. :param queue: the boto3 queue resource :param entries: [{'Id': 'str id', 'ReceiptHandle': 'str'}, ...] """ processed, response = 0, {'Successful': [], 'Failed': []} while processed < len(entries): try: next_batch = entries[processed:min((processed+10), len(entries))] next_resp = queue.delete_messages(Entries=next_batch) response['Successful'].extend(next_resp.get('Successful')) response['Failed'].extend(next_resp.get('Failed', [])) processed += len(next_batch) except Exception as e: logger.info( 'Message: Failure on SQS.Queue batch message delete - Error: {err} - QueueUrl: {queue_url}'.format( err=str(type(e)) + str(e), queue_url=queue.url ) ) raise e return response def send_sqs_messages(queue, messages, is_fifo_queue=False): """ can only send 10 per batch. that sucks. i want more. :param queue: the boto3 queue resource :param entries: list of dictionaries each of the form { 'message_body': (optional) json serializable blob, default = whole blob 'id': (optional) str, default = str(int corresponding to input list index) 'message_deduplication_id': (optional) str, default = guid 'message_group_id': (optional) str, default = '1' so all messages in same group } """ BOTO3_MAXIMUM_INPUT = 10 def to_message_parameters(id, message_blob, is_fifo): input_params = dict( Id=message_blob.get('id') or id, MessageBody=json.dumps(message_blob.get('message_body') or message_blob) ) if is_fifo: input_params.update( MessageDeduplicationId=message_blob.get('message_deduplication_id') or str(uuid.uuid4()), MessageGroupId=message_blob.get('message_group_id') or '1', ) return input_params response = dict(Successful=[], Failed=[]) try: for batch_number, message_batch in enumerate(list_to_batches(messages, BOTO3_MAXIMUM_INPUT)): as_valid_input_params = [ to_message_parameters(str(batch_number*BOTO3_MAXIMUM_INPUT + i), message, is_fifo_queue) for i, message in enumerate(message_batch) ] batch_response = queue.send_messages(Entries=as_valid_input_params) response['Successful'].extend(batch_response.get('Successful') or []) response['Failed'].extend(batch_response.get('Failed') or []) except Exception as e: logger.info( 'Message: Failure on SQS.Queue batch send message - Error: {err} - QueueUrl: {queue_url}'.format( err=str(type(e)) + str(e), queue_url=queue.url ) ) raise e return response _object_info_fields = [ 'bucket_name', 'bucket_arn', 'object_key', 'object_eTag', 'object_sequencer', 'object_size', 'region', 'event_name', 'event_version', 'event_time' ] S3EventObjectInfo = namedtuple('S3EventObjectInfo', _object_info_fields) def sqs_s3_messages(sqs_message): def to_s3_event_summary(record): # full message format https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html s3_bucket = record.get('s3').get('bucket') s3_object = record.get('s3').get('object') return S3EventObjectInfo( s3_bucket.get('name'), s3_bucket.get('arn'), s3_object.get('key'), s3_object.get('eTag'), s3_object.get('sequencer'), s3_object.get('size'), record.get('awsRegion'), record.get('eventName'), record.get('eventVersion'), record.get('eventTime') ) filtered_fields_messages = [SqsMessageEventRecord(to_s3_event_summary(rec), sqs_message) for rec in json.loads(sqs_message.body['Message']).get('Records', []) if 's3' in rec] return filtered_fields_messages def latest_s3_message_by_key(sqs_s3_msgs): if not sqs_s3_msgs: return [] kv = {(msg.event_record.object_key, msg.event_record.object_sequencer): msg for msg in sqs_s3_msgs} list_agg = {u_k: [] for u_k in set(k for k, _ in kv.keys())} for k, v in kv.keys(): list_agg[k].append(v) latest = [(k, sorted(v)[-1]) for k, v in list_agg.items()] return [kv[latest_kv] for latest_kv in latest] class SqsQueue(object): def __init__(self, queue_name, message_transformer=None, sqs_resource=None): self.queue_name = queue_name self.sqs_resource = sqs_resource or boto3.resource('sqs') self.queue = None self.message_transformer = message_transformer def get_queue(self): self.queue = self.sqs_resource.get_queue_by_name(QueueName=self.queue_name) return self def approximate_number_of_messages(self): return queue_approximate_number_of_messages(self.queue) def fifo_queue(self): return (self.queue.attributes.get('FifoQueue') or '').lower() == 'true' def has_messages(self): return self.approximate_number_of_messages() > 0 def receive_messages(self, **kwargs): update_func = self.message_transformer if self.message_transformer else (lambda m: [m]) return list(chain(*[update_func(msg) for msg in query_sqs_messages(queue=self.queue, **kwargs)])) def delete_messages(self, messages): try: resp = delete_sqs_messages(self.queue, entries=to_sqs_delete_entries(messages)) successful = resp.get('Successful', []) success_ct = len(successful) log_msg = 'Message: Removed messages from queue - DeletedMessageCount: {} - DeletedAllMessages: {}' logger.info(log_msg.format(success_ct, len(messages) == success_ct)) failed = resp.get('Failed', []) if failed: log_msg = 'Message: Subset of SQS.Queue batch delete calls failed - FailedDeletes: {}' logger.info(log_msg.format([dict(messages[fail['Id']], **fail) for fail in failed])) return resp except: pass def send_messages(self, messages): return send_sqs_messages(self.queue, messages, self.fifo_queue())
zdpy
/zdpy-0.1.0.tar.gz/zdpy-0.1.0/src/zd/boop/aws/sqs.py
sqs.py
Zds Member ========== |Build Status| |Build appveyor| |codecov.io| |Coverage Status| |PyPi version| Zds Member it’s a fork of `zds-site`_ member app to make a reusable application. zds-member ---------- zds-member is a django application that allows to manage members of website. Features -------- - Sign in (email or username) - Sign up (with email confirmation) - Reset password - Update users settings (email, username, password) - Unsubscribe - Sanction (ban, read only) - Geolocation - REST API (Json, Xml) - A lot of templates Requirements ------------ - Django 1.7 or 1.8 - Python 2.7, 3.3 or 3.4 Documentation ------------- See http://zds-member.readthedocs.org/ for documentation. |Documentation Status| .. _zds-site: https://github.com/zestedesavoir/zds-site .. |Build Status| image:: https://travis-ci.org/firm1/zds-member.svg?branch=master :target: https://travis-ci.org/firm1/zds-member .. |Build appveyor| image:: https://ci.appveyor.com/api/projects/status/dfoytnaqpuq1yhdk?svg=true :target: https://ci.appveyor.com/project/firm1/zds-member .. |codecov.io| image:: https://codecov.io/github/firm1/zds-member/coverage.svg?branch=master :target: https://codecov.io/github/firm1/zds-member?branch=master .. |Coverage Status| image:: https://coveralls.io/repos/firm1/zds-member/badge.svg?branch=master&service=github :target: https://coveralls.io/github/firm1/zds-member?branch=master .. |PyPi version| image:: https://img.shields.io/pypi/v/zds-member.svg :target: https://pypi.python.org/pypi/zds-member .. |Documentation Status| image:: https://readthedocs.org/projects/zds-member/badge/?version=latest :target: http://zds-member.readthedocs.org/en/latest/?badge=latest
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/README.rst
README.rst
============ Installation ============ Install the development version:: pip install zds-member Add ``member`` to your ``INSTALLED_APPS`` setting:: INSTALLED_APPS = ( # ... "member", # ... ) See the list of :ref:`settings` to modify the default behavior of zds-member and make adjustments for your website. Add ``member.urls`` to your URLs definition:: urlpatterns = patterns("", ... url(r"^members/", include("member.urls")), ... ) Once everything is in place make sure you run ``syncdb`` (Django 1.4 and 1.6) or ``migrate`` (Django 1.7) to modify the database with the ``member`` app models.
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/source/install.rst
install.rst
Undocumented Python objects =========================== member.forms ------------ Classes: * ChangePasswordForm * ChangeUserForm -- missing methods: - clean - throw_error * KarmaForm * NewPasswordForm -- missing methods: - clean * RegisterForm -- missing methods: - throw_error * UsernameAndEmailForm member.models ------------- Classes: * KarmaNote -- missing methods: - get_next_by_create_at - get_previous_by_create_at * TokenForgotPassword -- missing methods: - get_next_by_date_end - get_previous_by_date_end * TokenRegister -- missing methods: - get_next_by_date_end - get_previous_by_date_end member.views ------------ Classes: * MemberDetail -- missing methods: - get_context_data - get_object * RegisterView -- missing methods: - form_valid - get_form - get_object - get_success_template - post * SendValidationEmailView -- missing methods: - form_valid - get_error_message - get_form - get_success_template - get_user - post * UpdateMember -- missing methods: - dispatch - form_valid - get_error_message - get_form - get_object - get_success_message - get_success_url - post - save_profile - update_profile * UpdatePasswordMember -- missing methods: - get_form - get_success_message - get_success_url - post - update_profile * UpdateUsernameEmailMember -- missing methods: - get_form - get_success_url - update_profile
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/source/python.rst
python.rst
======== REST API ======== Member's Infos ============== List ---- .. http:get:: /api/ List of website's members :query page_size: number of users. default is 10 :statuscode 200: no error Details ------- .. http:get:: /api/(int:user_id)/ Gets a user given by its identifier. **Example request**: .. sourcecode:: http GET /api/800/ HTTP/1.1 Host: example.com Accept: application/json, text/javascript **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript { "pk": 800, "username": "firm1", "is_active": true, "date_joined": "2014-07-28T02:57:31", "site": "http://zestedesavoir.com", "avatar_url": "http://static.wamiz.fr/images/animaux/rongeurs/large/souris.jpg", "biography": "I'm beautiful", "sign": "cool", "show_email": false, "show_sign": true, "hover_or_click": true, "email_for_answer": false, "last_visit": "2015-10-20T03:24:06" } :param user_id: user's unique id :type user_id: int :statuscode 200: no error :statuscode 404: there's no user with this id .. http:get:: /api/mon-profil/ Gets informations about identified member :statuscode 200: no error :statuscode 401: user are not authenticated :reqheader Authorization: OAuth2 token to authenticate .. http:put:: /api/(int:user_id)/ Updates a user given by its identifier. :param user_id: user's unique id :type user_id: int :jsonparam int pk: user's unique id :statuscode 200: no error :statuscode 404: there's no user with this id :reqheader Authorization: OAuth2 token to authenticate Sanctions ========= Read Only --------- .. http:post:: /api/(int:user_id)/lecture-seule/ Applies a read only sanction at a user given. :param user_id: user's unique id :type user_id: int :jsonparam int pk: user id to read only :jsonparam string ls-jrs: Number of days for the sanction. :jsonparam string ls-text: Description of the sanction. :statuscode 200: no error :statuscode 401: Not authenticated :statuscode 403: Insufficient rights to call this procedure. Must to be a staff user. :statuscode 401: Not found :reqheader Authorization: OAuth2 token to authenticate .. http:delete:: /api/(int:user_id)/lecture-seule Removes a read only sanction at a user given. :param user_id: user's unique id :type user_id: int :jsonparam int pk: id of read only user :statuscode 200: no error :statuscode 401: Not authenticated :statuscode 403: Insufficient rights to call this procedure. Must to be a staff user. :statuscode 401: Not found :reqheader Authorization: OAuth2 token to authenticate Ban --- .. http:post:: /api/(int:user_id)/ban/ Applies a ban sanction at a user given. :param user_id: user's unique id :type user_id: int :jsonparam int pk: user id to ban :jsonparam string ban-jrs: Number of days for the sanction. :jsonparam string ban-text: Description of the sanction. :statuscode 200: no error :statuscode 401: Not authenticated :statuscode 403: Insufficient rights to call this procedure. Must to be a staff user. :statuscode 401: Not found :reqheader Authorization: OAuth2 token to authenticate .. http:delete:: /api/(int:user_id)/ban/ Removes a ban sanction at a user given. :param user_id: user's unique id :type user_id: int :jsonparam int pk: id of banned user :statuscode 200: no error :statuscode 401: Not authenticated :statuscode 403: Insufficient rights to call this procedure. Must to be a staff user. :statuscode 401: Not found :reqheader Authorization: OAuth2 token to authenticate
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/source/api.rst
api.rst
======== Features ======== Sign up ======== The registration of a member is in two phases: - The member creates their account and provides a username, a password and valid email address. - A confirmation email is sent with a token that will activate the account. .. Warning:: - Commas are not allowed in the nickname, which also can not begin or end with spaces. - The password must be at least 6 characters. Unsuscribe ========== Promote member ============== In order to manage the members directly from the site (ie without having to go through the Django admin interface), a promote interface was developed. This interface allows: 1. Add / Remove a member / group (s) 2. Add / Delete superuser status to a member 3. (De) activate an account First point allows to pass a member in new group. If other groups are emerging (validator) then it will be possible here also to change it. The second point can provide access to the member at the django interface and this promotion interface. Finally, the last point simply concerns the account activation (normally made by the Member at registration). It is managed by the PromoteMemberForm form available in the ``zds/member/forms.py``. It's then visible through the template ``member/settings/promote.html`` that may be accessed as root user by the profile of any member. Add karma ========= Reset Password ============== When a member forgets their password, you can reset it. The old password is deleted and the user can choose a new one. For this, he went on the password reset page (``members/reinitialisation /) from the login page. On this page the user has to enter his username or email address. For this, click on the link to the form. When the user clicks the submit button, a token is randomly generated and is stored in a database. A message is sent to the user's email address. This email contains a reset link. This link contains a parameter, the reset token and directs the user to address ``members/new_password/``. This page allows you to change the user's password. The user completes the form and clicks the submit button. If the password and the confirmation field and the corresponding password is business rules, the password is changed. The system displays a message confirming the password change. .. Warning:: - The password must be at least 6 characters. - The link is valid for one hour. If the user does not click on the link in the allotted time, an error message is displayed. - The password reset token is valid only once. If the user tries to change their password with the same token, a 404 page is displayed to the user.
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/source/features.rst
features.rst
============= Configuration ============= Configuration and list of available settings for zds-member Specifying files ---------------- .. code:: python ZDS_MEMBER = { 'bot_account': "admin", 'anonymous_account': "anonymous", 'external_account': "external", 'bot_group': 'bot', 'members_per_page': 100, } APP_SITE = { 'name': u"ZesteDeSavoir", 'litteral_name': u"Zeste de Savoir", 'email_noreply': "[email protected]", } ZDS_MEMBER_SETTINGS = { 'paginator': { 'folding_limit': 4 } } Url --- in ``url.py`` ``(r'^members/', include('member.urls'))`` Templates --------- A complete set of working templates is provided with the application. You may use it as it is with a CSS design of yours, re-use it or extend some parts of it. Relations between templates: .. code:: text base.html |_ member | |_ base.html | |_ index.html | |_ login.html | |_ profile.html | |_ register | | |_ base.html | | |_ index.html | | |_ send_validation_email.html | | |_ send_validation_email_success.html | | |_ success.html | | |_ token_already_used.html | | |_ token_failed.html | | |_ token_success.html | |_ settings | | |_ account.html | | |_ base.html | | |_ memberip.html | | |_ profile.html | | |_ promote.html | | |_ unregister.html | | |_ user.html | |_ new_password | |_ forgot_password |_ misc | |_ badge.part.html | |_ member_item.part.html
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/source/configure.rst
configure.rst
Search.setIndex({envversion:46,filenames:["api","configure","features","index","install","python","reference","usage"],objects:{"":{"/api/":[0,0,1,"get--api-"],"/api/(int:user_id)/":[0,1,1,"put--api-(int-user_id)-"],"/api/(int:user_id)/ban/":[0,3,1,"delete--api-(int-user_id)-ban-"],"/api/(int:user_id)/lecture-seule":[0,3,1,"delete--api-(int-user_id)-lecture-seule"],"/api/(int:user_id)/lecture-seule/":[0,2,1,"post--api-(int-user_id)-lecture-seule-"],"/api/mon-profil/":[0,0,1,"get--api-mon-profil-"]},"member.forms":{ChangeUserForm:[6,5,1,""],LoginForm:[6,5,1,""],MiniProfileForm:[6,5,1,""],NewPasswordForm:[6,5,1,""],ProfileForm:[6,5,1,""],PromoteMemberForm:[6,5,1,""],RegisterForm:[6,5,1,""]},"member.forms.RegisterForm":{clean:[6,7,1,""]},"member.models":{Ban:[6,5,1,""],KarmaNote:[6,5,1,""],Profile:[6,5,1,""],TokenForgotPassword:[6,5,1,""],TokenRegister:[6,5,1,""],auto_delete_token_on_unregistering:[6,6,1,""],logout_user:[6,6,1,""]},"member.models.Profile":{can_read_now:[6,7,1,""],can_write_now:[6,7,1,""],get_absolute_url:[6,7,1,""],get_avatar_url:[6,7,1,""],get_city:[6,7,1,""],is_private:[6,7,1,""]},"member.models.TokenForgotPassword":{get_absolute_url:[6,7,1,""]},"member.models.TokenRegister":{get_absolute_url:[6,7,1,""]},"member.views":{MemberDetail:[6,5,1,""],MemberList:[6,5,1,""],RegisterView:[6,5,1,""],SendValidationEmailView:[6,5,1,""],UpdateMember:[6,5,1,""],UpdatePasswordMember:[6,5,1,""],UpdateUsernameEmailMember:[6,5,1,""],active_account:[6,6,1,""],forgot_password:[6,6,1,""],generate_token_account:[6,6,1,""],get_client_ip:[6,6,1,""],login_view:[6,6,1,""],logout_view:[6,6,1,""],member_from_ip:[6,6,1,""],modify_karma:[6,6,1,""],new_password:[6,6,1,""],settings_promote:[6,6,1,""],unregister:[6,6,1,""],warning_unregister:[6,6,1,""]},"member.views.MemberDetail":{model:[6,8,1,""]},"member.views.RegisterView":{form_class:[6,8,1,""]},"member.views.UpdateMember":{form_class:[6,8,1,""]},"member.views.UpdateUsernameEmailMember":{form_class:[6,8,1,""]},member:{forms:[6,4,0,"-"],models:[6,4,0,"-"],views:[6,4,0,"-"]}},objnames:{"0":["http","get","HTTP get"],"1":["http","put","HTTP put"],"2":["http","post","HTTP post"],"3":["http","delete","HTTP delete"],"4":["py","module","Python module"],"5":["py","class","Python class"],"6":["py","function","Python function"],"7":["py","method","Python method"],"8":["py","attribute","Python attribute"]},objtypes:{"0":"http:get","1":"http:put","2":"http:post","3":"http:delete","4":"py:module","5":"py:class","6":"py:function","7":"py:method","8":"py:attribute"},terms:{"20t03":0,"28t02":0,"break":6,"class":[5,6],"default":[0,4,7],"final":2,"int":0,"new":[2,6],"return":6,"static":0,"super":6,"true":[0,6],about:[0,6],absolut:6,accept:0,access:[2,6],account:[1,2,6],activ:[2,6],active_account:6,address:[2,6],adjust:4,admin:[1,2,6],alia:6,all:6,allot:2,allow:[2,6],also:[2,6],ani:[2,6],animaux:0,anonym:1,anonymous_account:1,app:[3,4],app_sit:1,appli:0,applic:[0,1,3],arbitrari:6,arg:6,auth:6,authent:0,author:0,auto_delete_token_on_unregist:6,avail:[1,2],avatar:6,avatar_url:0,back:[],bad:6,badg:1,base:1,beauti:0,been:6,begin:[2,6],behavior:4,belong:6,between:1,biographi:[0,6],bool:6,bot:[1,6],bot_account:1,bot_group:1,both:6,busi:2,button:2,call:0,can:[2,6,7],can_read_now:6,can_write_now:6,chang:2,changepasswordform:5,changeuserform:[5,6],charact:2,check:6,checkbox:6,choos:[2,6],citi:6,clean:[5,6],click:[2,6],client:6,code:0,com:[0,1],comma:[2,6],comment:6,complementari:6,complet:[1,2],concern:2,confirm:2,connect:6,contain:[2,6],content:[0,6],cool:0,correct:6,correspond:2,countri:6,creat:[2,6],css:1,current:6,custom:6,dai:0,data:6,databas:[2,4,6],date:6,date_join:0,dedic:6,defin:6,definit:[4,6],delet:[0,2,6],demand:6,describ:7,descript:0,design:1,detail:6,develop:[2,4],differ:6,direct:2,directli:2,dispatch:5,displai:[2,6],django:[2,4],doe:2,doesn:6,each:6,els:6,email:[2,6],email_for_answ:0,email_norepli:1,embed:6,emerg:2,empti:6,end:2,enter:2,error:[0,2,6],everybodi:6,everyth:4,exampl:[0,1,7],exist:6,exot:6,expir:6,extend:1,extern:1,external_account:1,fals:[0,6],field:2,firm1:0,first:2,folding_limit:1,follow:6,forbidden:[0,6],forbidden_email_provid:6,forget:2,forgot:6,forgot_password:[1,6],forgotten:6,fork:3,form:2,form_class:6,form_valid:5,found:0,from:[2,6],gener:[2,6],generate_token_account:6,geo:6,get:[0,6],get_absolute_url:6,get_avatar_url:6,get_citi:6,get_client_ip:6,get_context_data:5,get_error_messag:5,get_form:5,get_next_by_create_at:5,get_next_by_date_end:5,get_object:5,get_previous_by_create_at:5,get_previous_by_date_end:5,get_success_messag:5,get_success_templ:5,get_success_url:5,get_us:5,github:3,given:0,good:6,gravatar:6,group:[2,6],happen:6,have:[2,6],header:0,help:6,here:2,histori:6,host:0,hour:2,hover:6,hover_or_click:0,how:7,html:[1,2],http:0,identifi:[0,6],imag:0,imprecis:6,includ:[1,4,6],index:1,inform:0,input:6,instal:[],installed_app:4,instanc:6,insuffici:0,interfac:2,internet:6,ipv4:6,ipv6:6,is_act:0,is_priv:6,itself:6,javascript:0,jpg:0,json:0,karmaform:5,karmanot:[5,6],kwarg:6,larg:0,last:[2,6],last_visit:0,least:2,lectur:0,level:6,link:[2,6],list:[1,4,6],litteral_nam:1,local:6,log:6,login:[1,2,6],login_view:6,loginform:6,logout:6,logout_us:6,logout_view:6,made:2,mai:[1,2],mail:6,main:6,make:[3,4],manag:[2,6],member_from_ip:6,member_item:1,memberdetail:[5,6],memberip:1,memberlist:6,members_per_pag:1,menu:6,messag:[2,6],method:5,migrat:4,miniprofileform:6,misc:1,miss:5,model:4,moder:6,modifi:4,modify_karma:6,mon:0,must:[0,2,6],name:[1,6],neg:6,new_password:[1,2,6],newpasswordform:[5,6],next:6,nicknam:2,none:6,norepli:1,normal:2,note:6,number:0,oauth2:0,object:[],old:2,onc:[2,4],onli:2,order:2,other:2,out:6,page:[2,6],page_s:0,pagin:1,paramet:[0,2,6],part:1,particular:6,pass:2,pattern:4,perform:6,person:6,phase:2,physic:6,pip:4,place:4,point:2,possibl:2,post:[0,5],procedur:0,profil:[0,1,2,6],profileform:6,project:6,promotememberform:[2,6],prove:6,provid:[1,2,6],put:0,python:[],queri:0,randomli:2,react:6,real:6,reason:6,receiv:6,regist:[1,6],registerform:[5,6],registerview:[5,6],registr:[2,6],reinitialis:2,rel:6,relat:1,rememb:6,remov:[0,2],replac:7,request:[0,6],respons:0,retriev:6,reusabl:3,right:[0,6],rongeur:0,root:[2,6],rule:[2,6],run:4,same:[2,6],save_profil:5,savoir:1,second:2,see:4,send:6,send_validation_email:1,send_validation_email_success:1,sender:6,sendvalidationemailview:[5,6],sent:2,set:[1,2,4,6],settings_promot:6,seul:0,show:6,show_email:0,show_sign:0,signal:6,signatur:6,simpli:2,site:[0,2,3,6],some:[1,6],someth:6,souri:0,space:[2,6],staff:[0,6],standard:6,statu:[0,2],store:[2,6],str:6,string:0,stupid:6,submit:2,success:1,superus:2,sure:4,syncdb:4,system:[2,6],templat:2,temporarili:6,text:0,thei:6,thi:[0,2,6],through:[2,6],throw_error:5,time:2,token:[0,2,6],token_already_us:1,token_fail:1,token_success:1,tokenforgotpassword:[5,6],tokenregist:[5,6],tool:6,tri:2,two:2,txt:6,type:[0,6],unauthor:0,undocu:[],uniqu:[0,6],unregist:[1,6],updat:[0,6],update_profil:5,updatememb:[5,6],updatepasswordmemb:[5,6],updateusernameemailmemb:[5,6],url:4,urlpattern:4,usag:[],user:[0,1,2,6],user_id:0,usernam:[0,2,6],usernameandemailform:5,valid:[2,6],valu:6,vari:0,veri:6,version:4,view:[],visibl:2,wamiz:0,warn:6,warning_unregist:6,web:6,websit:[0,4,6],went:2,what:6,when:[2,6,7],which:2,without:2,work:[1,6],write:6,you:[1,2,4,6,7],your:[1,4],zds_member:1,zds_member_set:1,zest:1,zestedesavoir:[0,1]},titles:["REST API","Configuration","Features","Zds Member Documentation","Installation","Undocumented Python objects","Django Back-end","Usage"],titleterms:{add:2,api:0,back:6,ban:0,configur:1,custom:7,detail:0,django:6,document:[3,6],end:6,featur:2,file:[1,6],form:[5,6,7],info:0,instal:4,karma:2,list:0,member:[0,2,3,5],model:[5,6],object:5,onli:0,password:2,promot:2,python:5,read:0,reset:2,rest:0,sanction:0,sign:2,specifi:1,summari:3,templat:1,undocu:5,unsuscrib:2,url:1,usag:7,view:[5,6]}})
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/searchindex.js
searchindex.js
* select a different prefix for underscore */ $u = _.noConflict(); /** * make the code below compatible with browsers without * an installed firebug like debugger if (!window.console || !console.firebug) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; } */ /** * small helper function to urldecode strings */ jQuery.urldecode = function(x) { return decodeURIComponent(x).replace(/\+/g, ' '); }; /** * small helper function to urlencode strings */ jQuery.urlencode = encodeURIComponent; /** * This function returns the parsed url parameters of the * current request. Multiple values per key are supported, * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { if (typeof s == 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; for (var i = 0; i < parts.length; i++) { var tmp = parts[i].split('=', 2); var key = jQuery.urldecode(tmp[0]); var value = jQuery.urldecode(tmp[1]); if (key in result) result[key].push(value); else result[key] = [value]; } return result; }; /** * highlight a given string on a jquery object by wrapping it in * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { function highlight(node) { if (node.nodeType == 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) { var span = document.createElement("span"); span.className = className; span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { highlight(this); }); } } return this.each(function() { highlight(this); }); }; /* * backward compatibility for jQuery.browser * This will be supported until firefox bug is fixed. */ if (!jQuery.browser) { jQuery.uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; jQuery.browser = {}; jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; } /** * Small JavaScript module for the documentation. */ var Documentation = { init : function() { this.fixFirefoxAnchorBug(); this.highlightSearchWords(); this.initIndexTable(); }, /** * i18n support */ TRANSLATIONS : {}, PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; }, LOCALE : 'unknown', // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext : function(string) { var translated = Documentation.TRANSLATIONS[string]; if (typeof translated == 'undefined') return string; return (typeof translated == 'string') ? translated : translated[0]; }, ngettext : function(singular, plural, n) { var translated = Documentation.TRANSLATIONS[singular]; if (typeof translated == 'undefined') return (n == 1) ? singular : plural; return translated[Documentation.PLURALEXPR(n)]; }, addTranslations : function(catalog) { for (var key in catalog.messages) this.TRANSLATIONS[key] = catalog.messages[key]; this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); this.LOCALE = catalog.locale; }, /** * add context elements like header anchor links */ addContextElements : function() { $('div[id] > :header:first').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this headline')). appendTo(this); }); $('dt[id]').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this definition')). appendTo(this); }); }, /** * workaround a firefox stupidity * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 */ fixFirefoxAnchorBug : function() { if (document.location.hash) window.setTimeout(function() { document.location.href += ''; }, 10); }, /** * highlight the search words provided in the url in the text */ highlightSearchWords : function() { var params = $.getQueryParameters(); var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; if (terms.length) { var body = $('div.body'); if (!body.length) { body = $('body'); } window.setTimeout(function() { $.each(terms, function() { body.highlightText(this.toLowerCase(), 'highlighted'); }); }, 10); $('<p class="highlight-link"><a href="javascript:Documentation.' + 'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>') .appendTo($('#searchbox')); } }, /** * init the domain index toggle buttons */ initIndexTable : function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); if (src.substr(-9) == 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { togglers.click(); } }, /** * helper function to hide the search marks again */ hideSearchWords : function() { $('#searchbox .highlight-link').fadeOut(300); $('span.highlighted').removeClass('highlighted'); }, /** * make the url absolute */ makeURL : function(relativeURL) { return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; }, /** * get the current relative url */ getCurrentURL : function() { var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { if (this == '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); } }; // quick alias for translations _ = Documentation.gettext; $(document).ready(function() { Documentation.init(); });
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/_static/doctools.js
doctools.js
(function(){function q(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source== c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&q(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&q(a[h],c[h],d))))break;if(g){for(h in c)if(b.has(c, h)&&!f--)break;g=!f}}d.pop();return g}var r=this,G=r._,n={},k=Array.prototype,o=Object.prototype,i=k.slice,H=k.unshift,l=o.toString,I=o.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,p=k.indexOf,D=k.lastIndexOf,o=Array.isArray,J=Object.keys,s=Function.prototype.bind,b=function(a){return new m(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else r._=b;b.VERSION="1.3.1";var j=b.each= b.forEach=function(a,c,d){if(a!=null)if(w&&a.forEach===w)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(d,a[e],e,a)===n)break}else for(e in a)if(b.has(a,e)&&c.call(d,a[e],e,a)===n)break};b.map=b.collect=function(a,c,b){var e=[];if(a==null)return e;if(x&&a.map===x)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});if(a.length===+a.length)e.length=a.length;return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=arguments.length>2;a== null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect= function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e= e&&c.call(b,a,g,h)))return n});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return n});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return p&&a.indexOf===p?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck= function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})}); return e.value};b.shuffle=function(a){var b=[],d;j(a,function(a,f){f==0?b[0]=a:(d=Math.floor(Math.random()*(f+1)),b[f]=b[d],b[d]=a)});return b};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a, c,d){d||(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest= b.tail=function(a,b,d){return i.call(a,b==null||d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]); return e};b.union=function(){return b.uniq(b.flatten(arguments,true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c, d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(p&&a.indexOf===p)return a.indexOf(c);for(d=0,e=a.length;d<e;d++)if(d in a&&a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(D&&a.lastIndexOf===D)return a.lastIndexOf(b);for(var d=a.length;d--;)if(d in a&&a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g}; var F=function(){};b.bind=function(a,c){var d,e;if(a.bind===s&&s)return s.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));F.prototype=a.prototype;var b=new F,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a, c){var d={};c||(c=b.identity);return function(){var e=c.apply(this,arguments);return b.has(d,e)?d[e]:d[e]=a.apply(this,arguments)}};b.delay=function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true: a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments,0));return b.apply(this,d)}};b.compose=function(){var a=arguments;return function(){for(var b=arguments,d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}}; b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=J||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.defaults=function(a){j(i.call(arguments, 1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return q(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=o||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)}; b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!b.has(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"}; b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a,b){return I.call(a,b)};b.noConflict=function(){r._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;")};b.mixin=function(a){j(b.functions(a), function(c){K(c,b[c]=a[c])})};var L=0;b.uniqueId=function(a){var b=L++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var t=/.^/,u=function(a){return a.replace(/\\\\/g,"\\").replace(/\\'/g,"'")};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||t,function(a,b){return"',_.escape("+ u(b)+"),'"}).replace(d.interpolate||t,function(a,b){return"',"+u(b)+",'"}).replace(d.evaluate||t,function(a,b){return"');"+u(b).replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var v=function(a,c){return c?b(a).chain():a},K=function(a,c){m.prototype[a]= function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.chain=function(){this._chain= true;return this};m.prototype.value=function(){return this._wrapped}}).call(this);
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/_static/underscore.js
underscore.js
(function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `global` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var slice = ArrayProto.slice, unshift = ArrayProto.unshift, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { return new wrapper(obj); }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root['_'] = _; } // Current version. _.VERSION = '1.3.1'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; } } else { for (var key in obj) { if (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results[results.length] = iterator.call(context, value, index, list); }); if (obj.length === +obj.length) results.length = obj.length; return results; }; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError('Reduce of empty array with no initial value'); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var reversed = _.toArray(obj).reverse(); if (context && !initial) iterator = _.bind(iterator, context); return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator); }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { var results = []; if (obj == null) return results; each(obj, function(value, index, list) { if (!iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if a given value is included in the array or object using `===`. // Aliased as `contains`. _.include = _.contains = function(obj, target) { var found = false; if (obj == null) return found; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; found = any(obj, function(value) { return value === target; }); return found; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); return _.map(obj, function(value) { return (_.isFunction(method) ? method || value : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, function(value){ return value[key]; }); }; // Return the maximum element or (element-based computation). _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed >= result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array. _.shuffle = function(obj) { var shuffled = [], rand; each(obj, function(value, index, list) { if (index == 0) { shuffled[0] = value; } else { rand = Math.floor(Math.random() * (index + 1)); shuffled[index] = shuffled[rand]; shuffled[rand] = value; } }); return shuffled; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, iterator, context) { return _.pluck(_.map(obj, function(value, index, list) { return { value : value, criteria : iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }), 'value'); }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = function(obj, val) { var result = {}; var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; each(obj, function(value, index) { var key = iterator(value, index); (result[key] || (result[key] = [])).push(value); }); return result; }; // Use a comparator function to figure out at what index an object should // be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator) { iterator || (iterator = _.identity); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >> 1; iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; } return low; }; // Safely convert anything iterable into a real, live array. _.toArray = function(iterable) { if (!iterable) return []; if (iterable.toArray) return iterable.toArray(); if (_.isArray(iterable)) return slice.call(iterable); if (_.isArguments(iterable)) return slice.call(iterable); return _.values(iterable); }; // Return the number of elements in an object. _.size = function(obj) { return _.toArray(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head`. The **guard** check allows it to work // with `_.map`. _.first = _.head = function(array, n, guard) { return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; }; // Returns everything but the last entry of the array. Especcialy useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if ((n != null) && !guard) { return slice.call(array, Math.max(array.length - n, 0)); } else { return array[array.length - 1]; } }; // Returns everything but the first entry of the array. Aliased as `tail`. // Especially useful on the arguments object. Passing an **index** will return // the rest of the values in the array from that index onward. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = function(array, index, guard) { return slice.call(array, (index == null) || guard ? 1 : index); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, function(value){ return !!value; }); }; // Return a completely flattened version of an array. _.flatten = function(array, shallow) { return _.reduce(array, function(memo, value) { if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); memo[memo.length] = value; return memo; }, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator) { var initial = iterator ? _.map(array, iterator) : array; var result = []; _.reduce(initial, function(memo, el, i) { if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) { memo[memo.length] = el; result[result.length] = array[i]; } return memo; }, []); return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. (Aliased as "intersect" for back-compat.) _.intersection = _.intersect = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = _.flatten(slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.include(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var args = slice.call(arguments); var length = _.max(_.pluck(args, 'length')); var results = new Array(length); for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); return results; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i, l; if (isSorted) { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item) { if (array == null) return -1; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); var i = array.length; while (i--) if (i in array && array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var len = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(len); while(idx < len) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Binding with arguments is also known as `curry`. // Delegates to **ECMAScript 5**'s native `Function.bind` if available. // We check for `func.bind` first, to fail fast when `func` is undefined. _.bind = function bind(func, context) { var bound, args; if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length == 0) funcs = _.functions(obj); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(func, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. _.throttle = function(func, wait) { var context, args, timeout, throttling, more; var whenDone = _.debounce(function(){ more = throttling = false; }, wait); return function() { context = this; args = arguments; var later = function() { timeout = null; if (more) func.apply(context, args); whenDone(); }; if (!timeout) timeout = setTimeout(later, wait); if (throttling) { more = true; } else { func.apply(context, args); } whenDone(); throttling = true; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. _.debounce = function(func, wait) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; return memo = func.apply(this, arguments); }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return function() { var args = [func].concat(slice.call(arguments, 0)); return wrapper.apply(this, args); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { if (times <= 0) return func(); return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { return _.map(obj, _.identity); }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { for (var prop in source) { obj[prop] = source[prop]; } }); return obj; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { for (var prop in source) { if (obj[prop] == null) obj[prop] = source[prop]; } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function. function eq(a, b, stack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a._chain) a = a._wrapped; if (b._chain) b = b._wrapped; // Invoke a custom `isEqual` method if one is provided. if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = stack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (stack[length] == a) return true; } // Add the first object to the stack of traversed objects. stack.push(a); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { // Ensure commutative equality for sparse arrays. if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; } } } else { // Objects with different constructors are not equivalent. if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. stack.pop(); return result; } // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType == 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Is a given variable an arguments object? _.isArguments = function(obj) { return toString.call(obj) == '[object Arguments]'; }; if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Is a given value a function? _.isFunction = function(obj) { return toString.call(obj) == '[object Function]'; }; // Is a given value a string? _.isString = function(obj) { return toString.call(obj) == '[object String]'; }; // Is a given value a number? _.isNumber = function(obj) { return toString.call(obj) == '[object Number]'; }; // Is the given value `NaN`? _.isNaN = function(obj) { // `NaN` is the only value for which `===` is not reflexive. return obj !== obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value a date? _.isDate = function(obj) { return toString.call(obj) == '[object Date]'; }; // Is the given value a regular expression? _.isRegExp = function(obj) { return toString.call(obj) == '[object RegExp]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Has own property? _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; // Run a function **n** times. _.times = function (n, iterator, context) { for (var i = 0; i < n; i++) iterator.call(context, i); }; // Escape a string for HTML interpolation. _.escape = function(string) { return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;'); }; // Add your own custom functions to the Underscore object, ensuring that // they're correctly added to the OOP wrapper as well. _.mixin = function(obj) { each(_.functions(obj), function(name){ addToWrapper(name, _[name] = obj[name]); }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = idCounter++; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /.^/; // Within an interpolation, evaluation, or escaping, remove HTML escaping // that had been previously added. var unescape = function(code) { return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'"); }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(str, data) { var c = _.templateSettings; var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + 'with(obj||{}){__p.push(\'' + str.replace(/\\/g, '\\\\') .replace(/'/g, "\\'") .replace(c.escape || noMatch, function(match, code) { return "',_.escape(" + unescape(code) + "),'"; }) .replace(c.interpolate || noMatch, function(match, code) { return "'," + unescape(code) + ",'"; }) .replace(c.evaluate || noMatch, function(match, code) { return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('"; }) .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') .replace(/\t/g, '\\t') + "');}return __p.join('');"; var func = new Function('obj', '_', tmpl); if (data) return func(data, _); return function(data) { return func.call(this, data, _); }; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // The OOP Wrapper // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. var wrapper = function(obj) { this._wrapped = obj; }; // Expose `wrapper.prototype` as `_.prototype` _.prototype = wrapper.prototype; // Helper function to continue chaining intermediate results. var result = function(obj, chain) { return chain ? _(obj).chain() : obj; }; // A method to easily add functions to the OOP wrapper. var addToWrapper = function(name, func) { wrapper.prototype[name] = function() { var args = slice.call(arguments); unshift.call(args, this._wrapped); return result(func.apply(_, args), this._chain); }; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; wrapper.prototype[name] = function() { var wrapped = this._wrapped; method.apply(wrapped, arguments); var length = wrapped.length; if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0]; return result(wrapped, this._chain); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; wrapper.prototype[name] = function() { return result(method.apply(this._wrapped, arguments), this._chain); }; }); // Start chaining a wrapped Underscore object. wrapper.prototype.chain = function() { this._chain = true; return this; }; // Extracts the result from a wrapped and chained object. wrapper.prototype.value = function() { return this._wrapped; }; }).call(this);
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/_static/underscore-1.3.1.js
underscore-1.3.1.js
(function($) { $.fn.autogrow = function() { return this.each(function() { var textarea = this; $.fn.autogrow.resize(textarea); $(textarea) .focus(function() { textarea.interval = setInterval(function() { $.fn.autogrow.resize(textarea); }, 500); }) .blur(function() { clearInterval(textarea.interval); }); }); }; $.fn.autogrow.resize = function(textarea) { var lineHeight = parseInt($(textarea).css('line-height'), 10); var lines = textarea.value.split('\n'); var columns = textarea.cols; var lineCount = 0; $.each(lines, function() { lineCount += Math.ceil(this.length / columns) || 1; }); var height = lineHeight * (lineCount + 1); $(textarea).css('height', height); }; })(jQuery); (function($) { var comp, by; function init() { initEvents(); initComparator(); } function initEvents() { $(document).on("click", 'a.comment-close', function(event) { event.preventDefault(); hide($(this).attr('id').substring(2)); }); $(document).on("click", 'a.vote', function(event) { event.preventDefault(); handleVote($(this)); }); $(document).on("click", 'a.reply', function(event) { event.preventDefault(); openReply($(this).attr('id').substring(2)); }); $(document).on("click", 'a.close-reply', function(event) { event.preventDefault(); closeReply($(this).attr('id').substring(2)); }); $(document).on("click", 'a.sort-option', function(event) { event.preventDefault(); handleReSort($(this)); }); $(document).on("click", 'a.show-proposal', function(event) { event.preventDefault(); showProposal($(this).attr('id').substring(2)); }); $(document).on("click", 'a.hide-proposal', function(event) { event.preventDefault(); hideProposal($(this).attr('id').substring(2)); }); $(document).on("click", 'a.show-propose-change', function(event) { event.preventDefault(); showProposeChange($(this).attr('id').substring(2)); }); $(document).on("click", 'a.hide-propose-change', function(event) { event.preventDefault(); hideProposeChange($(this).attr('id').substring(2)); }); $(document).on("click", 'a.accept-comment', function(event) { event.preventDefault(); acceptComment($(this).attr('id').substring(2)); }); $(document).on("click", 'a.delete-comment', function(event) { event.preventDefault(); deleteComment($(this).attr('id').substring(2)); }); $(document).on("click", 'a.comment-markup', function(event) { event.preventDefault(); toggleCommentMarkupBox($(this).attr('id').substring(2)); }); } /** * Set comp, which is a comparator function used for sorting and * inserting comments into the list. */ function setComparator() { // If the first three letters are "asc", sort in ascending order // and remove the prefix. if (by.substring(0,3) == 'asc') { var i = by.substring(3); comp = function(a, b) { return a[i] - b[i]; }; } else { // Otherwise sort in descending order. comp = function(a, b) { return b[by] - a[by]; }; } // Reset link styles and format the selected sort option. $('a.sel').attr('href', '#').removeClass('sel'); $('a.by' + by).removeAttr('href').addClass('sel'); } /** * Create a comp function. If the user has preferences stored in * the sortBy cookie, use those, otherwise use the default. */ function initComparator() { by = 'rating'; // Default to sort by rating. // If the sortBy cookie is set, use that instead. if (document.cookie.length > 0) { var start = document.cookie.indexOf('sortBy='); if (start != -1) { start = start + 7; var end = document.cookie.indexOf(";", start); if (end == -1) { end = document.cookie.length; by = unescape(document.cookie.substring(start, end)); } } } setComparator(); } /** * Show a comment div. */ function show(id) { $('#ao' + id).hide(); $('#ah' + id).show(); var context = $.extend({id: id}, opts); var popup = $(renderTemplate(popupTemplate, context)).hide(); popup.find('textarea[name="proposal"]').hide(); popup.find('a.by' + by).addClass('sel'); var form = popup.find('#cf' + id); form.submit(function(event) { event.preventDefault(); addComment(form); }); $('#s' + id).after(popup); popup.slideDown('fast', function() { getComments(id); }); } /** * Hide a comment div. */ function hide(id) { $('#ah' + id).hide(); $('#ao' + id).show(); var div = $('#sc' + id); div.slideUp('fast', function() { div.remove(); }); } /** * Perform an ajax request to get comments for a node * and insert the comments into the comments tree. */ function getComments(id) { $.ajax({ type: 'GET', url: opts.getCommentsURL, data: {node: id}, success: function(data, textStatus, request) { var ul = $('#cl' + id); var speed = 100; $('#cf' + id) .find('textarea[name="proposal"]') .data('source', data.source); if (data.comments.length === 0) { ul.html('<li>No comments yet.</li>'); ul.data('empty', true); } else { // If there are comments, sort them and put them in the list. var comments = sortComments(data.comments); speed = data.comments.length * 100; appendComments(comments, ul); ul.data('empty', false); } $('#cn' + id).slideUp(speed + 200); ul.slideDown(speed); }, error: function(request, textStatus, error) { showError('Oops, there was a problem retrieving the comments.'); }, dataType: 'json' }); } /** * Add a comment via ajax and insert the comment into the comment tree. */ function addComment(form) { var node_id = form.find('input[name="node"]').val(); var parent_id = form.find('input[name="parent"]').val(); var text = form.find('textarea[name="comment"]').val(); var proposal = form.find('textarea[name="proposal"]').val(); if (text == '') { showError('Please enter a comment.'); return; } // Disable the form that is being submitted. form.find('textarea,input').attr('disabled', 'disabled'); // Send the comment to the server. $.ajax({ type: "POST", url: opts.addCommentURL, dataType: 'json', data: { node: node_id, parent: parent_id, text: text, proposal: proposal }, success: function(data, textStatus, error) { // Reset the form. if (node_id) { hideProposeChange(node_id); } form.find('textarea') .val('') .add(form.find('input')) .removeAttr('disabled'); var ul = $('#cl' + (node_id || parent_id)); if (ul.data('empty')) { $(ul).empty(); ul.data('empty', false); } insertComment(data.comment); var ao = $('#ao' + node_id); ao.find('img').attr({'src': opts.commentBrightImage}); if (node_id) { // if this was a "root" comment, remove the commenting box // (the user can get it back by reopening the comment popup) $('#ca' + node_id).slideUp(); } }, error: function(request, textStatus, error) { form.find('textarea,input').removeAttr('disabled'); showError('Oops, there was a problem adding the comment.'); } }); } /** * Recursively append comments to the main comment list and children * lists, creating the comment tree. */ function appendComments(comments, ul) { $.each(comments, function() { var div = createCommentDiv(this); ul.append($(document.createElement('li')).html(div)); appendComments(this.children, div.find('ul.comment-children')); // To avoid stagnating data, don't store the comments children in data. this.children = null; div.data('comment', this); }); } /** * After adding a new comment, it must be inserted in the correct * location in the comment tree. */ function insertComment(comment) { var div = createCommentDiv(comment); // To avoid stagnating data, don't store the comments children in data. comment.children = null; div.data('comment', comment); var ul = $('#cl' + (comment.node || comment.parent)); var siblings = getChildren(ul); var li = $(document.createElement('li')); li.hide(); // Determine where in the parents children list to insert this comment. for(i=0; i < siblings.length; i++) { if (comp(comment, siblings[i]) <= 0) { $('#cd' + siblings[i].id) .parent() .before(li.html(div)); li.slideDown('fast'); return; } } // If we get here, this comment rates lower than all the others, // or it is the only comment in the list. ul.append(li.html(div)); li.slideDown('fast'); } function acceptComment(id) { $.ajax({ type: 'POST', url: opts.acceptCommentURL, data: {id: id}, success: function(data, textStatus, request) { $('#cm' + id).fadeOut('fast'); $('#cd' + id).removeClass('moderate'); }, error: function(request, textStatus, error) { showError('Oops, there was a problem accepting the comment.'); } }); } function deleteComment(id) { $.ajax({ type: 'POST', url: opts.deleteCommentURL, data: {id: id}, success: function(data, textStatus, request) { var div = $('#cd' + id); if (data == 'delete') { // Moderator mode: remove the comment and all children immediately div.slideUp('fast', function() { div.remove(); }); return; } // User mode: only mark the comment as deleted div .find('span.user-id:first') .text('[deleted]').end() .find('div.comment-text:first') .text('[deleted]').end() .find('#cm' + id + ', #dc' + id + ', #ac' + id + ', #rc' + id + ', #sp' + id + ', #hp' + id + ', #cr' + id + ', #rl' + id) .remove(); var comment = div.data('comment'); comment.username = '[deleted]'; comment.text = '[deleted]'; div.data('comment', comment); }, error: function(request, textStatus, error) { showError('Oops, there was a problem deleting the comment.'); } }); } function showProposal(id) { $('#sp' + id).hide(); $('#hp' + id).show(); $('#pr' + id).slideDown('fast'); } function hideProposal(id) { $('#hp' + id).hide(); $('#sp' + id).show(); $('#pr' + id).slideUp('fast'); } function showProposeChange(id) { $('#pc' + id).hide(); $('#hc' + id).show(); var textarea = $('#pt' + id); textarea.val(textarea.data('source')); $.fn.autogrow.resize(textarea[0]); textarea.slideDown('fast'); } function hideProposeChange(id) { $('#hc' + id).hide(); $('#pc' + id).show(); var textarea = $('#pt' + id); textarea.val('').removeAttr('disabled'); textarea.slideUp('fast'); } function toggleCommentMarkupBox(id) { $('#mb' + id).toggle(); } /** Handle when the user clicks on a sort by link. */ function handleReSort(link) { var classes = link.attr('class').split(/\s+/); for (var i=0; i<classes.length; i++) { if (classes[i] != 'sort-option') { by = classes[i].substring(2); } } setComparator(); // Save/update the sortBy cookie. var expiration = new Date(); expiration.setDate(expiration.getDate() + 365); document.cookie= 'sortBy=' + escape(by) + ';expires=' + expiration.toUTCString(); $('ul.comment-ul').each(function(index, ul) { var comments = getChildren($(ul), true); comments = sortComments(comments); appendComments(comments, $(ul).empty()); }); } /** * Function to process a vote when a user clicks an arrow. */ function handleVote(link) { if (!opts.voting) { showError("You'll need to login to vote."); return; } var id = link.attr('id'); if (!id) { // Didn't click on one of the voting arrows. return; } // If it is an unvote, the new vote value is 0, // Otherwise it's 1 for an upvote, or -1 for a downvote. var value = 0; if (id.charAt(1) != 'u') { value = id.charAt(0) == 'u' ? 1 : -1; } // The data to be sent to the server. var d = { comment_id: id.substring(2), value: value }; // Swap the vote and unvote links. link.hide(); $('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id) .show(); // The div the comment is displayed in. var div = $('div#cd' + d.comment_id); var data = div.data('comment'); // If this is not an unvote, and the other vote arrow has // already been pressed, unpress it. if ((d.value !== 0) && (data.vote === d.value * -1)) { $('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide(); $('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show(); } // Update the comments rating in the local data. data.rating += (data.vote === 0) ? d.value : (d.value - data.vote); data.vote = d.value; div.data('comment', data); // Change the rating text. div.find('.rating:first') .text(data.rating + ' point' + (data.rating == 1 ? '' : 's')); // Send the vote information to the server. $.ajax({ type: "POST", url: opts.processVoteURL, data: d, error: function(request, textStatus, error) { showError('Oops, there was a problem casting that vote.'); } }); } /** * Open a reply form used to reply to an existing comment. */ function openReply(id) { // Swap out the reply link for the hide link $('#rl' + id).hide(); $('#cr' + id).show(); // Add the reply li to the children ul. var div = $(renderTemplate(replyTemplate, {id: id})).hide(); $('#cl' + id) .prepend(div) // Setup the submit handler for the reply form. .find('#rf' + id) .submit(function(event) { event.preventDefault(); addComment($('#rf' + id)); closeReply(id); }) .find('input[type=button]') .click(function() { closeReply(id); }); div.slideDown('fast', function() { $('#rf' + id).find('textarea').focus(); }); } /** * Close the reply form opened with openReply. */ function closeReply(id) { // Remove the reply div from the DOM. $('#rd' + id).slideUp('fast', function() { $(this).remove(); }); // Swap out the hide link for the reply link $('#cr' + id).hide(); $('#rl' + id).show(); } /** * Recursively sort a tree of comments using the comp comparator. */ function sortComments(comments) { comments.sort(comp); $.each(comments, function() { this.children = sortComments(this.children); }); return comments; } /** * Get the children comments from a ul. If recursive is true, * recursively include childrens' children. */ function getChildren(ul, recursive) { var children = []; ul.children().children("[id^='cd']") .each(function() { var comment = $(this).data('comment'); if (recursive) comment.children = getChildren($(this).find('#cl' + comment.id), true); children.push(comment); }); return children; } /** Create a div to display a comment in. */ function createCommentDiv(comment) { if (!comment.displayed && !opts.moderator) { return $('<div class="moderate">Thank you! Your comment will show up ' + 'once it is has been approved by a moderator.</div>'); } // Prettify the comment rating. comment.pretty_rating = comment.rating + ' point' + (comment.rating == 1 ? '' : 's'); // Make a class (for displaying not yet moderated comments differently) comment.css_class = comment.displayed ? '' : ' moderate'; // Create a div for this comment. var context = $.extend({}, opts, comment); var div = $(renderTemplate(commentTemplate, context)); // If the user has voted on this comment, highlight the correct arrow. if (comment.vote) { var direction = (comment.vote == 1) ? 'u' : 'd'; div.find('#' + direction + 'v' + comment.id).hide(); div.find('#' + direction + 'u' + comment.id).show(); } if (opts.moderator || comment.text != '[deleted]') { div.find('a.reply').show(); if (comment.proposal_diff) div.find('#sp' + comment.id).show(); if (opts.moderator && !comment.displayed) div.find('#cm' + comment.id).show(); if (opts.moderator || (opts.username == comment.username)) div.find('#dc' + comment.id).show(); } return div; } /** * A simple template renderer. Placeholders such as <%id%> are replaced * by context['id'] with items being escaped. Placeholders such as <#id#> * are not escaped. */ function renderTemplate(template, context) { var esc = $(document.createElement('div')); function handle(ph, escape) { var cur = context; $.each(ph.split('.'), function() { cur = cur[this]; }); return escape ? esc.text(cur || "").html() : cur; } return template.replace(/<([%#])([\w\.]*)\1>/g, function() { return handle(arguments[2], arguments[1] == '%' ? true : false); }); } /** Flash an error message briefly. */ function showError(message) { $(document.createElement('div')).attr({'class': 'popup-error'}) .append($(document.createElement('div')) .attr({'class': 'error-message'}).text(message)) .appendTo('body') .fadeIn("slow") .delay(2000) .fadeOut("slow"); } /** Add a link the user uses to open the comments popup. */ $.fn.comment = function() { return this.each(function() { var id = $(this).attr('id').substring(1); var count = COMMENT_METADATA[id]; var title = count + ' comment' + (count == 1 ? '' : 's'); var image = count > 0 ? opts.commentBrightImage : opts.commentImage; var addcls = count == 0 ? ' nocomment' : ''; $(this) .append( $(document.createElement('a')).attr({ href: '#', 'class': 'sphinx-comment-open' + addcls, id: 'ao' + id }) .append($(document.createElement('img')).attr({ src: image, alt: 'comment', title: title })) .click(function(event) { event.preventDefault(); show($(this).attr('id').substring(2)); }) ) .append( $(document.createElement('a')).attr({ href: '#', 'class': 'sphinx-comment-close hidden', id: 'ah' + id }) .append($(document.createElement('img')).attr({ src: opts.closeCommentImage, alt: 'close', title: 'close' })) .click(function(event) { event.preventDefault(); hide($(this).attr('id').substring(2)); }) ); }); }; var opts = { processVoteURL: '/_process_vote', addCommentURL: '/_add_comment', getCommentsURL: '/_get_comments', acceptCommentURL: '/_accept_comment', deleteCommentURL: '/_delete_comment', commentImage: '/static/_static/comment.png', closeCommentImage: '/static/_static/comment-close.png', loadingImage: '/static/_static/ajax-loader.gif', commentBrightImage: '/static/_static/comment-bright.png', upArrow: '/static/_static/up.png', downArrow: '/static/_static/down.png', upArrowPressed: '/static/_static/up-pressed.png', downArrowPressed: '/static/_static/down-pressed.png', voting: false, moderator: false }; if (typeof COMMENT_OPTIONS != "undefined") { opts = jQuery.extend(opts, COMMENT_OPTIONS); } var popupTemplate = '\ <div class="sphinx-comments" id="sc<%id%>">\ <p class="sort-options">\ Sort by:\ <a href="#" class="sort-option byrating">best rated</a>\ <a href="#" class="sort-option byascage">newest</a>\ <a href="#" class="sort-option byage">oldest</a>\ </p>\ <div class="comment-header">Comments</div>\ <div class="comment-loading" id="cn<%id%>">\ loading comments... <img src="<%loadingImage%>" alt="" /></div>\ <ul id="cl<%id%>" class="comment-ul"></ul>\ <div id="ca<%id%>">\ <p class="add-a-comment">Add a comment\ (<a href="#" class="comment-markup" id="ab<%id%>">markup</a>):</p>\ <div class="comment-markup-box" id="mb<%id%>">\ reStructured text markup: <i>*emph*</i>, <b>**strong**</b>, \ <code>``code``</code>, \ code blocks: <code>::</code> and an indented block after blank line</div>\ <form method="post" id="cf<%id%>" class="comment-form" action="">\ <textarea name="comment" cols="80"></textarea>\ <p class="propose-button">\ <a href="#" id="pc<%id%>" class="show-propose-change">\ Propose a change &#9657;\ </a>\ <a href="#" id="hc<%id%>" class="hide-propose-change">\ Propose a change &#9663;\ </a>\ </p>\ <textarea name="proposal" id="pt<%id%>" cols="80"\ spellcheck="false"></textarea>\ <input type="submit" value="Add comment" />\ <input type="hidden" name="node" value="<%id%>" />\ <input type="hidden" name="parent" value="" />\ </form>\ </div>\ </div>'; var commentTemplate = '\ <div id="cd<%id%>" class="sphinx-comment<%css_class%>">\ <div class="vote">\ <div class="arrow">\ <a href="#" id="uv<%id%>" class="vote" title="vote up">\ <img src="<%upArrow%>" />\ </a>\ <a href="#" id="uu<%id%>" class="un vote" title="vote up">\ <img src="<%upArrowPressed%>" />\ </a>\ </div>\ <div class="arrow">\ <a href="#" id="dv<%id%>" class="vote" title="vote down">\ <img src="<%downArrow%>" id="da<%id%>" />\ </a>\ <a href="#" id="du<%id%>" class="un vote" title="vote down">\ <img src="<%downArrowPressed%>" />\ </a>\ </div>\ </div>\ <div class="comment-content">\ <p class="tagline comment">\ <span class="user-id"><%username%></span>\ <span class="rating"><%pretty_rating%></span>\ <span class="delta"><%time.delta%></span>\ </p>\ <div class="comment-text comment"><#text#></div>\ <p class="comment-opts comment">\ <a href="#" class="reply hidden" id="rl<%id%>">reply &#9657;</a>\ <a href="#" class="close-reply" id="cr<%id%>">reply &#9663;</a>\ <a href="#" id="sp<%id%>" class="show-proposal">proposal &#9657;</a>\ <a href="#" id="hp<%id%>" class="hide-proposal">proposal &#9663;</a>\ <a href="#" id="dc<%id%>" class="delete-comment hidden">delete</a>\ <span id="cm<%id%>" class="moderation hidden">\ <a href="#" id="ac<%id%>" class="accept-comment">accept</a>\ </span>\ </p>\ <pre class="proposal" id="pr<%id%>">\ <#proposal_diff#>\ </pre>\ <ul class="comment-children" id="cl<%id%>"></ul>\ </div>\ <div class="clearleft"></div>\ </div>\ </div>'; var replyTemplate = '\ <li>\ <div class="reply-div" id="rd<%id%>">\ <form id="rf<%id%>">\ <textarea name="comment" cols="80"></textarea>\ <input type="submit" value="Add reply" />\ <input type="button" value="Cancel" />\ <input type="hidden" name="parent" value="<%id%>" />\ <input type="hidden" name="node" value="" />\ </form>\ </div>\ </li>'; $(document).ready(function() { init(); }); })(jQuery); $(document).ready(function() { // add comment anchors for all paragraphs that are commentable $('.sphinx-has-comment').comment(); // highlight search words in search results $("div.context").each(function() { var params = $.getQueryParameters(); var terms = (params.q) ? params.q[0].split(/\s+/) : []; var result = $(this); $.each(terms, function() { result.highlightText(this.toLowerCase(), 'highlighted'); }); }); // directly open comment window if requested var anchor = document.location.hash; if (anchor.substring(0, 9) == '#comment-') { $('#ao' + anchor.substring(9)).click(); document.location.hash = '#s' + anchor.substring(9); } });
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/_static/websupport.js
websupport.js
* Porter Stemmer */ var Stemmer = function() { var step2list = { ational: 'ate', tional: 'tion', enci: 'ence', anci: 'ance', izer: 'ize', bli: 'ble', alli: 'al', entli: 'ent', eli: 'e', ousli: 'ous', ization: 'ize', ation: 'ate', ator: 'ate', alism: 'al', iveness: 'ive', fulness: 'ful', ousness: 'ous', aliti: 'al', iviti: 'ive', biliti: 'ble', logi: 'log' }; var step3list = { icate: 'ic', ative: '', alize: 'al', iciti: 'ic', ical: 'ic', ful: '', ness: '' }; var c = "[^aeiou]"; // consonant var v = "[aeiouy]"; // vowel var C = c + "[^aeiouy]*"; // consonant sequence var V = v + "[aeiou]*"; // vowel sequence var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 var s_v = "^(" + C + ")?" + v; // vowel in stem this.stemWord = function (w) { var stem; var suffix; var firstch; var origword = w; if (w.length < 3) return w; var re; var re2; var re3; var re4; firstch = w.substr(0,1); if (firstch == "y") w = firstch.toUpperCase() + w.substr(1); // Step 1a re = /^(.+?)(ss|i)es$/; re2 = /^(.+?)([^s])s$/; if (re.test(w)) w = w.replace(re,"$1$2"); else if (re2.test(w)) w = w.replace(re2,"$1$2"); // Step 1b re = /^(.+?)eed$/; re2 = /^(.+?)(ed|ing)$/; if (re.test(w)) { var fp = re.exec(w); re = new RegExp(mgr0); if (re.test(fp[1])) { re = /.$/; w = w.replace(re,""); } } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1]; re2 = new RegExp(s_v); if (re2.test(stem)) { w = stem; re2 = /(at|bl|iz)$/; re3 = new RegExp("([^aeiouylsz])\\1$"); re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re2.test(w)) w = w + "e"; else if (re3.test(w)) { re = /.$/; w = w.replace(re,""); } else if (re4.test(w)) w = w + "e"; } } // Step 1c re = /^(.+?)y$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(s_v); if (re.test(stem)) w = stem + "i"; } // Step 2 re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step2list[suffix]; } // Step 3 re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step3list[suffix]; } // Step 4 re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; re2 = /^(.+?)(s|t)(ion)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); if (re.test(stem)) w = stem; } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1] + fp[2]; re2 = new RegExp(mgr1); if (re2.test(stem)) w = stem; } // Step 5 re = /^(.+?)e$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); re2 = new RegExp(meq1); re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) w = stem; } re = /ll$/; re2 = new RegExp(mgr1); if (re.test(w) && re2.test(w)) { re = /.$/; w = w.replace(re,""); } // and turn initial Y back to y if (firstch == "y") w = firstch.toLowerCase() + w.substr(1); return w; } } /** * Simple result scoring code. */ var Scorer = { // Implement the following function to further tweak the score for each result // The function takes a result array [filename, title, anchor, descr, score] // and returns the new score. /* score: function(result) { return result[4]; }, */ // query matches the full name of an object objNameMatch: 11, // or matches in the last dotted part of the object name objPartialMatch: 6, // Additive scores depending on the priority of the object objPrio: {0: 15, // used to be importantResults 1: 5, // used to be objectResults 2: -5}, // used to be unimportantResults // Used when the priority is not in the mapping. objPrioDefault: 0, // query found in title title: 15, // query found in terms term: 5 }; /** * Search Module */ var Search = { _index : null, _queued_query : null, _pulse_status : -1, init : function() { var params = $.getQueryParameters(); if (params.q) { var query = params.q[0]; $('input[name="q"]')[0].value = query; this.performSearch(query); } }, loadIndex : function(url) { $.ajax({type: "GET", url: url, data: null, dataType: "script", cache: true, complete: function(jqxhr, textstatus) { if (textstatus != "success") { document.getElementById("searchindexloader").src = url; } }}); }, setIndex : function(index) { var q; this._index = index; if ((q = this._queued_query) !== null) { this._queued_query = null; Search.query(q); } }, hasIndex : function() { return this._index !== null; }, deferQuery : function(query) { this._queued_query = query; }, stopPulse : function() { this._pulse_status = 0; }, startPulse : function() { if (this._pulse_status >= 0) return; function pulse() { var i; Search._pulse_status = (Search._pulse_status + 1) % 4; var dotString = ''; for (i = 0; i < Search._pulse_status; i++) dotString += '.'; Search.dots.text(dotString); if (Search._pulse_status > -1) window.setTimeout(pulse, 500); } pulse(); }, /** * perform a search for something (or wait until index is loaded) */ performSearch : function(query) { // create the required interface elements this.out = $('#search-results'); this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out); this.dots = $('<span></span>').appendTo(this.title); this.status = $('<p style="display: none"></p>').appendTo(this.out); this.output = $('<ul class="search"/>').appendTo(this.out); $('#search-progress').text(_('Preparing search...')); this.startPulse(); // index already loaded, the browser was quick! if (this.hasIndex()) this.query(query); else this.deferQuery(query); }, /** * execute search (requires search index to be loaded) */ query : function(query) { var i; var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"]; // stem the searchterms and add them to the correct list var stemmer = new Stemmer(); var searchterms = []; var excluded = []; var hlterms = []; var tmp = query.split(/\s+/); var objectterms = []; for (i = 0; i < tmp.length; i++) { if (tmp[i] !== "") { objectterms.push(tmp[i].toLowerCase()); } if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) || tmp[i] === "") { // skip this "word" continue; } // stem the word var word = stemmer.stemWord(tmp[i].toLowerCase()); var toAppend; // select the correct list if (word[0] == '-') { toAppend = excluded; word = word.substr(1); } else { toAppend = searchterms; hlterms.push(tmp[i].toLowerCase()); } // only add if not already in the list if (!$u.contains(toAppend, word)) toAppend.push(word); } var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" ")); // console.debug('SEARCH: searching for:'); // console.info('required: ', searchterms); // console.info('excluded: ', excluded); // prepare search var terms = this._index.terms; var titleterms = this._index.titleterms; // array of [filename, title, anchor, descr, score] var results = []; $('#search-progress').empty(); // lookup as object for (i = 0; i < objectterms.length; i++) { var others = [].concat(objectterms.slice(0, i), objectterms.slice(i+1, objectterms.length)); results = results.concat(this.performObjectSearch(objectterms[i], others)); } // lookup as search terms in fulltext results = results.concat(this.performTermsSearch(searchterms, excluded, terms, Scorer.term)) .concat(this.performTermsSearch(searchterms, excluded, titleterms, Scorer.title)); // let the scorer override scores with a custom scoring function if (Scorer.score) { for (i = 0; i < results.length; i++) results[i][4] = Scorer.score(results[i]); } // now sort the results by score (in opposite order of appearance, since the // display function below uses pop() to retrieve items) and then // alphabetically results.sort(function(a, b) { var left = a[4]; var right = b[4]; if (left > right) { return 1; } else if (left < right) { return -1; } else { // same score: sort alphabetically left = a[1].toLowerCase(); right = b[1].toLowerCase(); return (left > right) ? -1 : ((left < right) ? 1 : 0); } }); // for debugging //Search.lastresults = results.slice(); // a copy //console.info('search results:', Search.lastresults); // print the results var resultCount = results.length; function displayNextItem() { // results left, load the summary and display it if (results.length) { var item = results.pop(); var listItem = $('<li style="display:none"></li>'); if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') { // dirhtml builder var dirname = item[0] + '/'; if (dirname.match(/\/index\/$/)) { dirname = dirname.substring(0, dirname.length-6); } else if (dirname == 'index/') { dirname = ''; } listItem.append($('<a/>').attr('href', DOCUMENTATION_OPTIONS.URL_ROOT + dirname + highlightstring + item[2]).html(item[1])); } else { // normal html builders listItem.append($('<a/>').attr('href', item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX + highlightstring + item[2]).html(item[1])); } if (item[3]) { listItem.append($('<span> (' + item[3] + ')</span>')); Search.output.append(listItem); listItem.slideDown(5, function() { displayNextItem(); }); } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) { $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[0] + '.txt', dataType: "text", complete: function(jqxhr, textstatus) { var data = jqxhr.responseText; if (data !== '' && data !== undefined) { listItem.append(Search.makeSearchSummary(data, searchterms, hlterms)); } Search.output.append(listItem); listItem.slideDown(5, function() { displayNextItem(); }); }}); } else { // no source available, just display title Search.output.append(listItem); listItem.slideDown(5, function() { displayNextItem(); }); } } // search finished, update title and status message else { Search.stopPulse(); Search.title.text(_('Search Results')); if (!resultCount) Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.')); else Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount)); Search.status.fadeIn(500); } } displayNextItem(); }, /** * search for object names */ performObjectSearch : function(object, otherterms) { var filenames = this._index.filenames; var objects = this._index.objects; var objnames = this._index.objnames; var titles = this._index.titles; var i; var results = []; for (var prefix in objects) { for (var name in objects[prefix]) { var fullname = (prefix ? prefix + '.' : '') + name; if (fullname.toLowerCase().indexOf(object) > -1) { var score = 0; var parts = fullname.split('.'); // check for different match types: exact matches of full name or // "last name" (i.e. last dotted part) if (fullname == object || parts[parts.length - 1] == object) { score += Scorer.objNameMatch; // matches in last name } else if (parts[parts.length - 1].indexOf(object) > -1) { score += Scorer.objPartialMatch; } var match = objects[prefix][name]; var objname = objnames[match[1]][2]; var title = titles[match[0]]; // If more than one term searched for, we require other words to be // found in the name/title/description if (otherterms.length > 0) { var haystack = (prefix + ' ' + name + ' ' + objname + ' ' + title).toLowerCase(); var allfound = true; for (i = 0; i < otherterms.length; i++) { if (haystack.indexOf(otherterms[i]) == -1) { allfound = false; break; } } if (!allfound) { continue; } } var descr = objname + _(', in ') + title; var anchor = match[3]; if (anchor === '') anchor = fullname; else if (anchor == '-') anchor = objnames[match[1]][1] + '-' + fullname; // add custom score for some objects according to scorer if (Scorer.objPrio.hasOwnProperty(match[2])) { score += Scorer.objPrio[match[2]]; } else { score += Scorer.objPrioDefault; } results.push([filenames[match[0]], fullname, '#'+anchor, descr, score]); } } } return results; }, /** * search for full-text terms in the index */ performTermsSearch : function(searchterms, excluded, terms, score) { var filenames = this._index.filenames; var titles = this._index.titles; var i, j, file, files; var fileMap = {}; var results = []; // perform the search on the required terms for (i = 0; i < searchterms.length; i++) { var word = searchterms[i]; // no match but word was a required one if ((files = terms[word]) === undefined) break; if (files.length === undefined) { files = [files]; } // create the mapping for (j = 0; j < files.length; j++) { file = files[j]; if (file in fileMap) fileMap[file].push(word); else fileMap[file] = [word]; } } // now check if the files don't contain excluded terms for (file in fileMap) { var valid = true; // check if all requirements are matched if (fileMap[file].length != searchterms.length) continue; // ensure that none of the excluded terms is in the search result for (i = 0; i < excluded.length; i++) { if (terms[excluded[i]] == file || $u.contains(terms[excluded[i]] || [], file)) { valid = false; break; } } // if we have still a valid result we can add it to the result list if (valid) { results.push([filenames[file], titles[file], '', null, score]); } } return results; }, /** * helper function to return a node containing the * search summary for a given text. keywords is a list * of stemmed words, hlwords is the list of normal, unstemmed * words. the first one is used to find the occurance, the * latter for highlighting it. */ makeSearchSummary : function(text, keywords, hlwords) { var textLower = text.toLowerCase(); var start = 0; $.each(keywords, function() { var i = textLower.indexOf(this.toLowerCase()); if (i > -1) start = i; }); start = Math.max(start - 120, 0); var excerpt = ((start > 0) ? '...' : '') + $.trim(text.substr(start, 240)) + ((start + 240 - text.length) ? '...' : ''); var rv = $('<div class="context"></div>').text(excerpt); $.each(hlwords, function() { rv = rv.highlightText(this, 'highlighted'); }); return rv; } }; $(document).ready(function() { Search.init(); });
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/_static/searchtools.js
searchtools.js
function toggleCurrent (elem) { var parent_li = elem.closest('li'); parent_li.siblings('li.current').removeClass('current'); parent_li.siblings().find('li.current').removeClass('current'); parent_li.find('> ul li.current').removeClass('current'); parent_li.toggleClass('current'); } $(document).ready(function() { // Shift nav in mobile when clicking the menu. $(document).on('click', "[data-toggle='wy-nav-top']", function() { $("[data-toggle='wy-nav-shift']").toggleClass("shift"); $("[data-toggle='rst-versions']").toggleClass("shift"); }); // Nav menu link click operations $(document).on('click', ".wy-menu-vertical .current ul li a", function() { var target = $(this); // Close menu when you click a link. $("[data-toggle='wy-nav-shift']").removeClass("shift"); $("[data-toggle='rst-versions']").toggleClass("shift"); // Handle dynamic display of l3 and l4 nav lists toggleCurrent(target); if (typeof(window.SphinxRtdTheme) != 'undefined') { window.SphinxRtdTheme.StickyNav.hashChange(); } }); $(document).on('click', "[data-toggle='rst-current-version']", function() { $("[data-toggle='rst-versions']").toggleClass("shift-up"); }); // Make tables responsive $("table.docutils:not(.field-list)").wrap("<div class='wy-table-responsive'></div>"); // Add expand links to all parents of nested ul $('.wy-menu-vertical ul').siblings('a').each(function () { var link = $(this); expand = $('<span class="toctree-expand"></span>'); expand.on('click', function (ev) { toggleCurrent(link); ev.stopPropagation(); return false; }); link.prepend(expand); }); }); // Sphinx theme state window.SphinxRtdTheme = (function (jquery) { var stickyNav = (function () { var navBar, win, winScroll = false, linkScroll = false, winPosition = 0, enable = function () { init(); reset(); win.on('hashchange', reset); // Set scrolling win.on('scroll', function () { if (!linkScroll) { winScroll = true; } }); setInterval(function () { if (winScroll) { winScroll = false; var newWinPosition = win.scrollTop(), navPosition = navBar.scrollTop(), newNavPosition = navPosition + (newWinPosition - winPosition); navBar.scrollTop(newNavPosition); winPosition = newWinPosition; } }, 25); }, init = function () { navBar = jquery('nav.wy-nav-side:first'); win = jquery(window); }, reset = function () { // Get anchor from URL and open up nested nav var anchor = encodeURI(window.location.hash); if (anchor) { try { var link = $('.wy-menu-vertical') .find('[href="' + anchor + '"]'); $('.wy-menu-vertical li.toctree-l1 li.current') .removeClass('current'); link.closest('li.toctree-l2').addClass('current'); link.closest('li.toctree-l3').addClass('current'); link.closest('li.toctree-l4').addClass('current'); } catch (err) { console.log("Error expanding nav for anchor", err); } } }, hashChange = function () { linkScroll = true; win.one('hashchange', function () { linkScroll = false; }); }; jquery(init); return { enable: enable, hashChange: hashChange }; }()); return { StickyNav: stickyNav }; }($));
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/_static/js/theme.js
theme.js
;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)u[c[d]]=c[d]in k;return u.list&&(u.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),u}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:e=k.value!=l)),t[a[d]]=!!e;return t}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,e.prefixed=function(a,b,c){return b?J(a,b,c):J(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/doc/build/html/_static/js/modernizr.min.js
modernizr.min.js
from django.conf.urls import patterns, url, include from member.views import MemberList, MemberDetail, UpdateMember, UpdatePasswordMember, \ UpdateUsernameEmailMember, RegisterView, SendValidationEmailView urlpatterns = patterns('', #list url(r'^$', MemberList.as_view(), name='member-list'), #details url(r'^voir/(?P<user_name>.+)/$', MemberDetail.as_view(), name='member-detail'), #modification url(r'^parametres/profil/$', UpdateMember.as_view(), name='update-member'), url(r'^parametres/compte/$', UpdatePasswordMember.as_view(), name='update-password-member'), url(r'^parametres/user/$', UpdateUsernameEmailMember.as_view(), name='update-username-email-member'), #moderation url(r'^profil/karmatiser/$', 'member.views.modify_karma'), url(r'^profil/modifier/(?P<user_pk>\d+)/$', 'member.views.modify_profile'), url(r'^parametres/mini_profil/(?P<user_name>.+)/$', 'member.views.settings_mini_profile'), url(r'^profil/multi/(?P<ip_address>.+)/$', 'member.views.member_from_ip'), #user rights url(r'^profil/promouvoir/(?P<user_pk>\d+)/$', 'member.views.settings_promote'), #membership url(r'^connexion/$', 'member.views.login_view'), url(r'^deconnexion/$', 'member.views.logout_view'), url(r'^inscription/$', RegisterView.as_view(), name='register-member'), url(r'^reinitialisation/$', 'member.views.forgot_password'), url(r'^validation/$', SendValidationEmailView.as_view(), name='send-validation-email'), url(r'^new_password/$', 'member.views.new_password'), url(r'^activation/$', 'member.views.active_account'), url(r'^envoi_jeton/$', 'member.views.generate_token_account'), url(r'^desinscrire/valider/$', 'member.views.unregister'), url(r'^desinscrire/avertissement/$', 'member.views.warning_unregister') ) # API urlpatterns += patterns('', url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^api/', include('member.api.urls')), )
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/member/urls.py
urls.py
from datetime import datetime, timedelta import uuid from member.conf import settings from django.contrib.auth.models import User from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.template.defaultfilters import pluralize from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.models import Site from member.models import Profile, TokenRegister, Ban, logout_user class ProfileCreate(object): def create_profile(self, data): """ Creates an inactive profile in the database. :param data: Array about an user. :type data: array :return: instance of a profile inactive :rtype: Profile object """ username = data.get('username') email = data.get('email') password = data.get('password') user = User.objects.create_user(username, email, password) user.set_password(password) user.is_active = False user.backend = 'django.contrib.auth.backends.ModelBackend' profile = Profile(user=user, show_email=False, show_sign=True, hover_or_click=True, email_for_answer=False) return profile def save_profile(self, profile): """ Saves the profile of a member. :param profile: The profile of a member. :type data: Profile object :return: nothing :rtype: None """ profile.save() profile.user.save() class TokenGenerator(object): def generate_token(self, user): """ Generates a token for member registration. :param user: An User object. :type user: User object :return: A token object :rtype: Token object """ uuid_token = str(uuid.uuid4()) date_end = datetime.now() + timedelta(hours=1) token = TokenRegister(user=user, token=uuid_token, date_end=date_end) token.save() return token def send_email(self, token, user): """ Sends an email with a confirmation a registration which contain a link for registration validation. :param token: The token for registration validation. :type token: Token Object :param user: The user just registered. :type user: User object :return: nothing :rtype: None """ subject = _(u'{} - Confirmation d\'inscription').format(settings.APP_SITE['litteral_name']) from_email = u'{} <{}>'.format(settings.APP_SITE['litteral_name'], settings.APP_SITE['email_noreply']) current_site = Site.objects.get_current() context = { 'username': user.username, 'url': current_site.domain + token.get_absolute_url(), 'site_name': settings.APP_SITE['litteral_name'], 'site_url': current_site.domain } message_html = render_to_string('email/member/confirm_registration.html', context) message_txt = render_to_string('email/member/confirm_registration.txt', context) msg = EmailMultiAlternatives(subject, message_txt, from_email, [user.email]) msg.attach_alternative(message_html, 'text/html') try: msg.send() except Exception: pass class MemberSanctionState(object): """ Super class of the enumeration to know which sanction it is. """ array_infos = None def __init__(self, array_infos): super(MemberSanctionState, self).__init__() self.array_infos = array_infos def get_type(self): """ Gets the type of a sanction. :return: type of the sanction. :rtype: ugettext_lazy """ raise NotImplementedError('`get_type()` must be implemented.') def get_text(self): """ Gets the text of a sanction. :return: text of the sanction. :rtype: string """ raise NotImplementedError('`get_text()` must be implemented.') def get_detail(self): """ Gets detail of a sanction. :return: detail of the sanction. :rtype: ugettext_lazy """ raise NotImplementedError('`get_detail()` must be implemented.') def apply_sanction(self, profile, ban): """ Applies the sanction with the `ban` object on a member with the `profile` object and saves these objects. :param profile: Member concerned by the sanction. :type profile: Profile object :param ban: Sanction. :type ban: Ban object :return: nothing :rtype: None """ raise NotImplementedError('`apply_sanction()` must be implemented.') def get_sanction(self, moderator, user): """ Gets the sanction according to the type of the sanction. :param moderator: Moderator who applies the sanction. :type moderator: User object :param user: User sanctioned. :type user: User object :return: sanction :rtype: Ban object """ ban = Ban() ban.moderator = moderator ban.user = user ban.pubdate = datetime.now() ban.type = self.get_type() ban.text = self.get_text() return ban def get_message_unsanction(self): """ Gets the message for an un-sanction. :return: message of the un-sanction. :rtype: ugettext_lazy """ return _(u'Bonjour **{0}**,\n\n' u'**Bonne nouvelle**, la sanction qui ' u'pesait sur vous a été levée par **{1}**.\n\n' u'Ce qui signifie que {3}\n\n' u'Le motif est :\n\n' u'> {4}\n\n' u'Cordialement, \n\n L\'équipe {5}.') def get_message_sanction(self): """ Gets the message for a sanction. :return: message of the sanction. :rtype: ugettext_lazy """ return _(u'Bonjour **{0}**,\n\n' u'Vous avez été santionné par **{1}**.\n\n' u'La sanction est de type *{2}*, ce qui signifie que {3}\n\n' u'Le motif de votre sanction est :\n\n' u'> {4}\n\n' u'Cordialement, \n\nL\'équipe {5}.') def notify_member(self, ban, msg): """ Notify the member sanctioned with a MP. :param ban: Sanction. :type ban: Ban object :param msg: message send at the user sanctioned. :type msg: string object :return: nothing :rtype: None """ """ bot = get_object_or_404(User, username=settings.ZDS_MEMBER['bot_account']) send_mp( bot, [ban.user], ban.type, "", msg, True, direct=True, ) """ pass class ReadingOnlySanction(MemberSanctionState): """ State of the sanction reading only. """ def get_type(self): return _(u"Read only") def get_text(self): return self.array_infos.get('ls-text', '') def get_detail(self): return (_(u"You can't write on website ")) def apply_sanction(self, profile, ban): profile.end_ban_write = None profile.can_write = False profile.save() ban.save() class TemporaryReadingOnlySanction(MemberSanctionState): """ State of the sanction reading only temporary. """ def get_type(self): return _(u"Read only Temporary") def get_text(self): return self.array_infos.get('ls-text', '') def get_detail(self): jrs = int(self.array_infos.get("ls-jrs")) return (_(u"You can't write on website during {0} day{1}") .format(jrs, pluralize(jrs))) def apply_sanction(self, profile, ban): day = int(self.array_infos.get("ls-jrs")) profile.end_ban_write = datetime.now() + timedelta(days=day, hours=0, minutes=0, seconds=0) profile.can_write = False profile.save() ban.save() class DeleteReadingOnlySanction(MemberSanctionState): """ State of the un-sanction reading only. """ def get_type(self): return _(u"Permission to write") def get_text(self): return self.array_infos.get('unls-text', '') def get_detail(self): return (_(u'vous pouvez désormais poster sur les forums, dans les ' u'commentaires d\'articles et tutoriels.')) def apply_sanction(self, profile, ban): profile.can_write = True profile.end_ban_write = None profile.save() ban.save() class BanSanction(MemberSanctionState): """ State of the sanction ban. """ def get_type(self): return _(u"Ban definitive") def get_text(self): return self.array_infos.get('ban-text', '') def get_detail(self): return _(u"You can't log on {0}.") \ .format(settings.APP_SITE['litteral_name']) def apply_sanction(self, profile, ban): profile.end_ban_read = None profile.can_read = False profile.save() ban.save() logout_user(profile.user.username) class TemporaryBanSanction(MemberSanctionState): """ State of the sanction ban temporary. """ def get_type(self): return _(u"Ban Temporary") def get_text(self): return self.array_infos.get('ban-text', '') def get_detail(self): jrs = int(self.array_infos.get("ban-jrs")) return (_(u"You can't log on {0} during {1} day{2}.") .format(settings.APP_SITE['litteral_name'], jrs, pluralize(jrs))) def apply_sanction(self, profile, ban): day = int(self.array_infos.get("ban-jrs")) profile.end_ban_read = datetime.now() + timedelta(days=day, hours=0, minutes=0, seconds=0) profile.can_read = False profile.save() ban.save() logout_user(profile.user.username) class DeleteBanSanction(MemberSanctionState): """ State of the un-sanction ban. """ def get_type(self): return _(u"Permission to log on") def get_text(self): return self.array_infos.get('unban-text', '') def get_detail(self): return _(u"vous pouvez désormais vous connecter sur le site.") def apply_sanction(self, profile, ban): profile.can_read = True profile.end_ban_read = None profile.save() ban.save()
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/member/commons.py
commons.py
import os from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from member.utils.api.validators import Validator from member.conf import settings BASE_DIR = settings.BASE_DIR class ProfileUsernameValidator(Validator): """ Validates username field of a profile. """ def validate_username(self, value): """ Checks about the username. :param value: username value :type value: string :return: username value :rtype: string """ msg = None if value: if value.strip() == '': msg = _(u'Le nom d\'utilisateur ne peut-être vide') # Forbid the use of comma in the username elif "," in value: msg = _(u'Le nom d\'utilisateur ne peut contenir de virgules') elif value != value.strip(): msg = _(u'Le nom d\'utilisateur ne peut commencer/finir par des espaces') elif User.objects.filter(username=value).count() > 0: msg = _(u'Ce nom d\'utilisateur est déjà utilisé') if msg is not None: self.throw_error('username', msg) return value class ProfileEmailValidator(Validator): """ Validates email field of a profile. """ def validate_email(self, value): """ Checks about the email. :param value: email value :type value: string :return: email value :rtype: string """ if value: msg = None # Chech if email provider is authorized with open(os.path.join(BASE_DIR, 'forbidden_email_providers.txt'), 'r') as black_list: for provider in black_list: if provider.strip() in value: msg = _(u'Utilisez un autre fournisseur d\'adresses courriel.') break # Check that the email is unique if User.objects.filter(email=value).count() > 0: msg = _(u'Votre adresse courriel est déjà utilisée') if msg is not None: self.throw_error('email', msg) return value
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/member/validators.py
validators.py
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.utils.decorators import method_decorator def can_write_and_read_now(func): """ Checks if the current user has read and write rights, right now. A visitor has correct rights only if it is connected and has proper rights attached to its profile. Real roles in database are checked, this doesn't use session-cached stuff. :param func: the decorated function :return: `True` if the current user can read and write, `False` otherwise. """ def _can_write_and_read_now(request, *args, **kwargs): try: profile = request.user.profile except: # The user is a visitor profile = None if profile is not None: if not profile.can_read_now() or not profile.can_write_now(): raise PermissionDenied return func(request, *args, **kwargs) return _can_write_and_read_now class PermissionRequiredMixin(object): """ Represent the basic code that a Generic Class Based View has to use when one or more permissions are required simultaneously to execute the view """ permissions = [] def check_permissions(self): if False in [self.request.user.has_perm(p) for p in self.permissions]: raise PermissionDenied def dispatch(self, *args, **kwargs): self.check_permissions() return super(PermissionRequiredMixin, self).dispatch(*args, **kwargs) class LoginRequiredMixin(object): """ Represent the basic code that a Generic Class Based View has to use when the required action needs the user to be logged in. If the user is not logged in, the user is redirected to the connection form and the former action is not executed. """ @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) class LoggedWithReadWriteHability(LoginRequiredMixin): """ Represent the basic code that a Generic Class View has to use when a logged in user with read and write hability is required. """ @method_decorator(can_write_and_read_now) def dispatch(self, *args, **kwargs): return super(LoggedWithReadWriteHability, self).dispatch(*args, **kwargs)
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/member/decorator.py
decorator.py
from datetime import datetime, timedelta import uuid from member.conf import settings from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, Group from django.core.context_processors import csrf from django.core.exceptions import PermissionDenied from django.core.mail import EmailMultiAlternatives from django.core.urlresolvers import reverse from django.db import transaction from django.db.models import Q from django.utils.http import urlunquote from django.http import Http404, HttpResponseBadRequest from django.shortcuts import redirect, render, get_object_or_404 from django.template.loader import render_to_string from django.utils.decorators import method_decorator from django.utils.translation import ugettext_lazy as _ from django.views.decorators.http import require_POST from django.contrib.sites.models import Site from django.views.generic import DetailView, UpdateView, CreateView, FormView from member.forms import LoginForm, MiniProfileForm, ProfileForm, RegisterForm, \ ChangePasswordForm, ChangeUserForm, NewPasswordForm, \ PromoteMemberForm, KarmaForm, UsernameAndEmailForm from member.models import Profile, TokenForgotPassword, TokenRegister, KarmaNote from member.decorator import can_write_and_read_now from member.commons import ProfileCreate, TemporaryReadingOnlySanction, ReadingOnlySanction, \ DeleteReadingOnlySanction, TemporaryBanSanction, BanSanction, DeleteBanSanction, TokenGenerator from member.utils.paginator import ZdSPagingListView from member.utils.tokens import generate_token class MemberList(ZdSPagingListView): """Displays the list of registered users.""" context_object_name = 'members' paginate_by = settings.ZDS_MEMBER['members_per_page'] # TODO When User will be no more used, you can make this request with # Profile.objects.all_members_ordered_by_date_joined() queryset = User.objects.filter(is_active=True) \ .order_by('-date_joined') \ .all().select_related("profile") template_name = 'member/index.html' class MemberDetail(DetailView): """Displays details about a profile.""" context_object_name = 'usr' model = User template_name = 'member/profile.html' def get_object(self, queryset=None): # Use urlunquote to accept quoted twice URLs (for instance in MPs send # through emarkdown parser) return get_object_or_404(User, username=urlunquote(self.kwargs['user_name'])) def get_context_data(self, **kwargs): context = super(MemberDetail, self).get_context_data(**kwargs) usr = context['usr'] profile = usr.profile context['profile'] = profile context['karmanotes'] = KarmaNote.objects.filter(user=usr).order_by('-create_at') context['karmaform'] = KarmaForm(profile) return context class UpdateMember(UpdateView): """Updates a profile.""" form_class = ProfileForm template_name = 'member/settings/profile.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(UpdateMember, self).dispatch(*args, **kwargs) def get_object(self, queryset=None): return get_object_or_404(Profile, user=self.request.user) def get_form(self, form_class): profile = self.get_object() form = form_class(initial={ 'biography': profile.biography, 'site': profile.site, 'avatar_url': profile.avatar_url, 'show_email': profile.show_email, 'show_sign': profile.show_sign, 'hover_or_click': profile.hover_or_click, 'email_for_answer': profile.email_for_answer, 'sign': profile.sign }) return form def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): return self.form_valid(form) return render(request, self.template_name, {'form': form}) def form_valid(self, form): profile = self.get_object() self.update_profile(profile, form) self.save_profile(profile) return redirect(self.get_success_url()) def update_profile(self, profile, form): cleaned_data_options = form.cleaned_data.get('options') profile.biography = form.data['biography'] profile.site = form.data['site'] profile.show_email = 'show_email' in cleaned_data_options profile.show_sign = 'show_sign' in cleaned_data_options profile.hover_or_click = 'hover_or_click' in cleaned_data_options profile.email_for_answer = 'email_for_answer' in cleaned_data_options profile.avatar_url = form.data['avatar_url'] profile.sign = form.data['sign'] def get_success_url(self): return reverse('update-member') def save_profile(self, profile): try: profile.save() profile.user.save() except Profile.DoesNotExist: messages.error(self.request, self.get_error_message()) return redirect(reverse('update-member')) messages.success(self.request, self.get_success_message()) def get_success_message(self): return _(u'The profile has been updated.') def get_error_message(self): return _(u'An error has occurred.') class UpdatePasswordMember(UpdateMember): """User's settings about his password.""" form_class = ChangePasswordForm def post(self, request, *args, **kwargs): form = self.form_class(request.user, request.POST) if form.is_valid(): return self.form_valid(form) return render(request, self.template_name, {'form': form}) def get_form(self, form_class): return form_class(self.request.user) def update_profile(self, profile, form): profile.user.set_password(form.data['password_new']) def get_success_message(self): return _(u'The password has been updated.') def get_success_url(self): return reverse('update-password-member') class UpdateUsernameEmailMember(UpdateMember): """User's settings about his username and email.""" form_class = ChangeUserForm def get_form(self, form_class): return form_class(self.request.POST) def update_profile(self, profile, form): if 'username' in form.data: profile.user.username = form.data['username'] if 'email' in form.data: if form.data['email'].strip() != '': profile.user.email = form.data['email'] def get_success_url(self): profile = self.get_object() return profile.get_absolute_url() class RegisterView(CreateView, ProfileCreate, TokenGenerator): """Create a profile.""" form_class = RegisterForm template_name = 'member/register/index.html' def get_object(self, queryset=None): return get_object_or_404(Profile, user=self.request.user) def get_form(self, form_class): return form_class() def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): return self.form_valid(form) return render(request, self.template_name, {'form': form}) def form_valid(self, form): profile = self.create_profile(form.data) profile.last_ip_address = get_client_ip(self.request) self.save_profile(profile) token = self.generate_token(profile.user) self.send_email(token, profile.user) return render(self.request, self.get_success_template()) def get_success_template(self): return 'member/register/success.html' class SendValidationEmailView(FormView, TokenGenerator): """Send a validation email on demand. """ form_class = UsernameAndEmailForm template_name = 'member/register/send_validation_email.html' usr = None def get_user(self, username, email): if username: self.usr = get_object_or_404(User, username=username) elif email: self.usr = get_object_or_404(User, email=email) def get_form(self, form_class): return form_class() def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # Fetch the user if "username" in form.data: username = form.data["username"] else: username = None if "email" in form.data: email = form.data["email"] else: email = None self.get_user(username, email) # User should not be already active if not self.usr.is_active: return self.form_valid(form) else: if username is not None: form.errors['username'] = form.error_class([self.get_error_message()]) else: form.errors['email'] = form.error_class([self.get_error_message()]) return render(request, self.template_name, {'form': form}) def form_valid(self, form): # Delete old token token = TokenRegister.objects.filter(user=self.usr) if token.count() >= 1: token.all().delete() # Generate new token and send email token = self.generate_token(self.usr) self.send_email(token, self.usr) return render(self.request, self.get_success_template()) def get_success_template(self): return 'member/register/send_validation_email_success.html' def get_error_message(self): return _("Le compte est déjà activé.") @login_required def warning_unregister(request): """ Displays a warning page showing what will happen when user unregisters. """ return render(request, 'member/settings/unregister.html', {'user': request.user}) @login_required @require_POST @transaction.atomic def unregister(request): """allow members to unregister""" current = request.user logout(request) User.objects.filter(pk=current.pk).delete() return redirect("/") @require_POST @can_write_and_read_now @login_required @transaction.atomic def modify_profile(request, user_pk): """Modifies sanction of a user if there is a POST request.""" profile = get_object_or_404(Profile, user__pk=user_pk) if profile.is_private(): raise PermissionDenied if request.user.profile == profile: messages.error(request, _(u"You can't punish yourself!")) raise PermissionDenied if 'ls' in request.POST: state = ReadingOnlySanction(request.POST) elif 'ls-temp' in request.POST: state = TemporaryReadingOnlySanction(request.POST) elif 'ban' in request.POST: state = BanSanction(request.POST) elif 'ban-temp' in request.POST: state = TemporaryBanSanction(request.POST) elif 'un-ls' in request.POST: state = DeleteReadingOnlySanction(request.POST) else: # un-ban state = DeleteBanSanction(request.POST) try: ban = state.get_sanction(request.user, profile.user) except ValueError: raise HttpResponseBadRequest state.apply_sanction(profile, ban) if 'un-ls' in request.POST or 'un-ban' in request.POST: msg = state.get_message_unsanction() else: msg = state.get_message_sanction() msg = msg.format(ban.user, ban.moderator, ban.type, state.get_detail(), ban.text, settings.APP_SITE['litteral_name']) state.notify_member(ban, msg) return redirect(profile.get_absolute_url()) # settings for public profile @can_write_and_read_now @login_required def settings_mini_profile(request, user_name): """Minimal settings of users for staff.""" # extra information about the current user profile = get_object_or_404(Profile, user__username=user_name) if request.method == "POST": form = MiniProfileForm(request.POST) data = {"form": form, "profile": profile} if form.is_valid(): profile.biography = form.data["biography"] profile.site = form.data["site"] profile.avatar_url = form.data["avatar_url"] profile.sign = form.data["sign"] # Save the profile and redirect the user to the configuration space # with message indicate the state of the operation try: profile.save() except: messages.error(request, _(u"An error has occurred.")) return redirect(reverse("member.views.settings_mini_profile")) messages.success(request, _(u"The profile has been updated.")) return redirect(reverse("member-detail", args=[profile.user.username])) else: return render(request, "member/settings/profile.html", data) else: form = MiniProfileForm(initial={ "biography": profile.biography, "site": profile.site, "avatar_url": profile.avatar_url, "sign": profile.sign, }) data = {"form": form, "profile": profile} return render(request, "member/settings/profile.html", data) def login_view(request): """Log in user.""" csrf_tk = {} csrf_tk.update(csrf(request)) error = False # Redirecting user once logged in? if "next" in request.GET: next_page = request.GET["next"] else: next_page = None if request.method == "POST": form = LoginForm(request.POST) username = request.POST["username"] password = request.POST["password"] user = authenticate(username=username, password=password) if user is not None: profile = get_object_or_404(Profile, user=user) if user.is_active: if profile.can_read_now(): login(request, user) request.session["get_token"] = generate_token() if "remember" not in request.POST: request.session.set_expiry(0) profile.last_ip_address = get_client_ip(request) profile.save() # redirect the user if needed try: return redirect(next_page) except: return redirect("/") else: messages.error(request, _(u"You aren't allowed to connect " u"to the site, you have been banned by " u"a moderator.")) else: messages.error(request, _(u"You haven't activated your account, " u"you must do this before you can " u"log on the website. Look in your " u"mail : {}.").format(user.email)) else: messages.error(request, _(u"The information provided is not valid.")) if next_page is not None: form = LoginForm() form.helper.form_action += "?next=" + next_page else: form = LoginForm() csrf_tk["error"] = error csrf_tk["form"] = form csrf_tk["next_page"] = next_page return render(request, "member/login.html", {"form": form, "csrf_tk": csrf_tk}) @login_required @require_POST def logout_view(request): """Log out user.""" logout(request) request.session.clear() return redirect("/") def forgot_password(request): """If the user forgot his password, he can have a new one.""" if request.method == "POST": form = UsernameAndEmailForm(request.POST) if form.is_valid(): # Get data from form data = form.data username = data["username"] email = data["email"] # Fetch the user, we need his email adress usr = None if username: usr = get_object_or_404(User, Q(username=username)) if email: usr = get_object_or_404(User, Q(email=email)) # Generate a valid token during one hour. uuid_token = str(uuid.uuid4()) date_end = datetime.now() + timedelta(days=0, hours=1, minutes=0, seconds=0) token = TokenForgotPassword(user=usr, token=uuid_token, date_end=date_end) token.save() # send email subject = _(u"{} - Mot de passe oublié").format(settings.APP_SITE['litteral_name']) from_email = "{} <{}>".format(settings.APP_SITE['litteral_name'], settings.APP_SITE['email_noreply']) current_site = Site.objects.get_current() context = { "username": usr.username, "site_name": settings.APP_SITE['litteral_name'], "site_url": current_site.domain, "url": current_site.domain + token.get_absolute_url() } message_html = render_to_string("email/member/confirm_forgot_password.html", context) message_txt = render_to_string("email/member/confirm_forgot_password.txt", context) msg = EmailMultiAlternatives(subject, message_txt, from_email, [usr.email]) msg.attach_alternative(message_html, "text/html") msg.send() return render(request, "member/forgot_password/success.html") else: return render(request, "member/forgot_password/index.html", {"form": form}) form = UsernameAndEmailForm() return render(request, "member/forgot_password/index.html", {"form": form}) def new_password(request): """Create a new password for a user.""" try: token = request.GET["token"] except KeyError: return redirect("/") token = get_object_or_404(TokenForgotPassword, token=token) if request.method == "POST": form = NewPasswordForm(token.user.username, request.POST) if form.is_valid(): data = form.data password = data["password"] # User can't confirm his request if it is too late. if datetime.now() > token.date_end: return render(request, "member/new_password/failed.html") token.user.set_password(password) token.user.save() token.delete() return render(request, "member/new_password/success.html") else: return render(request, "member/new_password/index.html", {"form": form}) form = NewPasswordForm(identifier=token.user.username) return render(request, "member/new_password/index.html", {"form": form}) def active_account(request): """Active token for a user.""" try: token = request.GET["token"] except KeyError: return redirect("/") token = get_object_or_404(TokenRegister, token=token) usr = token.user # User can't confirm his request if he is already activated. if usr.is_active: return render(request, "member/register/token_already_used.html") # User can't confirm his request if it is too late. if datetime.now() > token.date_end: return render(request, "member/register/token_failed.html", {"token": token}) usr.is_active = True usr.save() # send register message """ current_site = Site.objects.get_current() bot = get_object_or_404(User, username=settings.ZDS_MEMBER['bot_account']) msg = _( u'Bonjour **{username}**,' u'\n\n' u'Ton compte a été activé, et tu es donc officiellement ' u'membre de la communauté de {site_name}.' u'\n\n' u'{site_name} est une communauté dont le but est de diffuser des ' u'connaissances au plus grand nombre.' u'\n\n' u'Sur ce site, tu trouveras un ensemble de [tutoriels]({tutorials_url}) dans ' u'plusieurs domaines et plus particulièrement autour de l\'informatique ' u'et des sciences. Tu y retrouveras aussi des [articles]({articles_url}) ' u'traitant de sujets d\'actualité ou non, qui, tout comme les tutoriels, ' u'sont écrits par des [membres]({members_url}) de la communauté. ' u'Pendant tes lectures et ton apprentissage, si jamais tu as des ' u'questions à poser, tu retrouveras sur les [forums]({forums_url}) des personnes ' u'prêtes à te filer un coup de main et ainsi t\'éviter de passer ' u'plusieurs heures sur un problème.' u'\n\n' u'L\'ensemble du contenu disponible sur le site est et sera toujours gratuit, ' u'car la communauté de {site_name} est attachée aux valeurs du libre ' u'partage et désire apporter le savoir à tout le monde quels que soient ses moyens.' u'\n\n' u'En espérant que tu te plairas ici, ' u'je te laisse maintenant faire un petit tour.' u'\n\n' u'Clem\'') \ .format(username=usr.username, tutorials_url=current_site.domain + reverse("tutorial:list"), articles_url=current_site.domain + reverse("article:list"), members_url=current_site.domain + reverse("member-list"), forums_url=current_site.domain + reverse('cats-forums-list'), site_name=settings.APP_SITE['litteral_name']) send_mp( bot, [usr], _(u"Bienvenue sur {}").format(settings.APP_SITE['litteral_name']), _(u"Le manuel du nouveau membre"), msg, True, True, False, ) """ token.delete() form = LoginForm(initial={'username': usr.username}) return render(request, "member/register/token_success.html", {"usr": usr, "form": form}) def generate_token_account(request): """Generate token for account.""" try: token = request.GET["token"] except KeyError: return redirect("/") token = get_object_or_404(TokenRegister, token=token) # push date date_end = datetime.now() + timedelta(days=0, hours=1, minutes=0, seconds=0) token.date_end = date_end token.save() # send email subject = _(u"{} - Registration confirmation").format(settings.APP_SITE['litteral_name']) from_email = "{} <{}>".format(settings.APP_SITE['litteral_name'], settings.APP_SITE['email_noreply']) current_site = Site.objects.get_current() context = { "username": token.user.username, "site_url": current_site.domain, "site_name": settings.APP_SITE['litteral_name'], "url": current_site.domain + token.get_absolute_url() } message_html = render_to_string("email/member/confirm_registration.html", context) message_txt = render_to_string("email/member/confirm_registration.txt", context) msg = EmailMultiAlternatives(subject, message_txt, from_email, [token.user.email]) msg.attach_alternative(message_html, "text/html") try: msg.send() except: msg = None return render(request, 'member/register/success.html', {}) def get_client_ip(request): """Retrieve the real IP address of the client.""" if "HTTP_X_REAL_IP" in request.META: # nginx return request.META.get("HTTP_X_REAL_IP") elif "REMOTE_ADDR" in request.META: # other return request.META.get("REMOTE_ADDR") else: # should never happend return "0.0.0.0" @login_required def settings_promote(request, user_pk): """ Manage the admin right of user. Only super user can access """ if not request.user.is_superuser: raise PermissionDenied profile = get_object_or_404(Profile, user__pk=user_pk) user = profile.user if request.method == "POST": form = PromoteMemberForm(request.POST) data = dict(form.data.lists()) groups = Group.objects.all() usergroups = user.groups.all() if 'groups' in data: for group in groups: if str(group.id) in data['groups']: if group not in usergroups: user.groups.add(group) messages.success(request, _(u'{0} now belongs to the group {1}.') .format(user.username, group.name)) else: if group in usergroups: user.groups.remove(group) messages.warning(request, _(u'{0} now no longer belongs to the group {1}.') .format(user.username, group.name)) else: user.groups.clear() messages.warning(request, _(u'{0} not now belong to any group.') .format(user.username)) if 'superuser' in data and u'on' in data['superuser']: if not user.is_superuser: user.is_superuser = True messages.success(request, _(u'{0} is now superuser.') .format(user.username)) else: if user == request.user: messages.error(request, _(u"A superuser can't to retire from super-users.")) else: if user.is_superuser: user.is_superuser = False messages.warning(request, _(u'{0} is no longer superuser.') .format(user.username)) if 'activation' in data and u'on' in data['activation']: user.is_active = True messages.success(request, _(u'{0} is now activated.') .format(user.username)) else: user.is_active = False messages.warning(request, _(u'{0} is now deactivated.') .format(user.username)) user.save() usergroups = user.groups.all() """ bot = get_object_or_404(User, username=settings.ZDS_MEMBER['bot_account']) msg = _(u'Bonjour {0},\n\n' u'Un administrateur vient de modifier les groupes ' u'auxquels vous appartenez. \n').format(user.username) if len(usergroups) > 0: msg = string_concat(msg, _(u'Voici la liste des groupes dont vous faites dorénavant partie :\n\n')) for group in usergroups: msg += u'* {0}\n'.format(group.name) else: msg = string_concat(msg, _(u'* Vous ne faites partie d\'aucun groupe')) msg += u'\n\n' if user.is_superuser: msg = string_concat(msg, _(u'Vous avez aussi rejoint le rang des super-utilisateurs. ' u'N\'oubliez pas, un grand pouvoir entraîne de grandes responsabilités !')) send_mp( bot, [user], _(u'Modification des groupes'), u'', msg, True, True, ) """ return redirect(profile.get_absolute_url()) form = PromoteMemberForm(initial={ 'superuser': user.is_superuser, 'groups': user.groups.all(), 'activation': user.is_active }) return render(request, 'member/settings/promote.html', { "usr": user, "profile": profile, "form": form }) @login_required def member_from_ip(request, ip_address): """ Get list of user connected from a particular ip """ if not request.user.has_perm("member.change_profile"): raise PermissionDenied members = Profile.objects.filter(last_ip_address=ip_address).order_by('-last_visit') return render(request, 'member/settings/memberip.html', { "members": members, "ip": ip_address }) @login_required @require_POST def modify_karma(request): """ Add a Karma note to the user profile """ if not request.user.has_perm("member.change_profile"): raise PermissionDenied try: profile_pk = request.POST["profile_pk"] except (KeyError, ValueError): raise Http404 profile = get_object_or_404(Profile, pk=profile_pk) if profile.is_private(): raise PermissionDenied note = KarmaNote() note.user = profile.user note.staff = request.user note.comment = request.POST["warning"] try: note.value = int(request.POST["points"]) except (KeyError, ValueError): note.value = 0 note.save() profile.karma += note.value profile.save() return redirect(reverse("member-detail", args=[profile.user.username]))
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/member/views.py
views.py
from django.contrib.auth.models import User, Permission, Group import factory from member.models import Profile class UserFactory(factory.DjangoModelFactory): """ This factory creates User. WARNING: Don't try to directly use `UserFactory`, this didn't create associated Profile then don't work! Use `ProfileFactory` instead. """ FACTORY_FOR = User username = factory.Sequence('firm{0}'.format) email = factory.Sequence('firm{0}@zestedesavoir.com'.format) password = 'hostel77' is_active = True @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', None) user = super(UserFactory, cls)._prepare(create, **kwargs) if password: user.set_password(password) if create: user.save() return user class StaffFactory(factory.DjangoModelFactory): """ This factory creates staff User. WARNING: Don't try to directly use `StaffFactory`, this didn't create associated Profile then don't work! Use `StaffProfileFactory` instead. """ FACTORY_FOR = User username = factory.Sequence('firmstaff{0}'.format) email = factory.Sequence('firmstaff{0}@zestedesavoir.com'.format) password = 'hostel77' is_active = True @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', None) user = super(StaffFactory, cls)._prepare(create, **kwargs) if password: user.set_password(password) if create: user.save() group_staff = Group.objects.filter(name="staff").first() if group_staff is None: group_staff = Group(name="staff") group_staff.save() perms = Permission.objects.filter(codename__startswith='change_').all() group_staff.permissions = perms user.groups.add(group_staff) user.save() return user class ProfileFactory(factory.DjangoModelFactory): """ Use this factory when you need a complete Profile for a standard user. """ FACTORY_FOR = Profile user = factory.SubFactory(UserFactory) last_ip_address = '192.168.2.1' site = 'www.zestedesavoir.com' @factory.lazy_attribute def biography(self): return u'My name is {0} and I i\'m the guy who kill the bad guys '.format(self.user.username.lower()) sign = 'Please look my flavour' class StaffProfileFactory(factory.DjangoModelFactory): """ Use this factory when you need a complete Profile for a staff user. """ FACTORY_FOR = Profile user = factory.SubFactory(StaffFactory) last_ip_address = '192.168.2.1' site = 'www.zestedesavoir.com' @factory.lazy_attribute def biography(self): return u'My name is {0} and I i\'m the guy who kill the bad guys '.format(self.user.username.lower()) sign = 'Please look my flavour' class NonAsciiUserFactory(UserFactory): """ This factory creates standard user with non-ASCII characters in its username. WARNING: Don't try to directly use `NonAsciiUserFactory`, this didn't create associated Profile then don't work! Use `NonAsciiProfileFactory` instead. """ FACTORY_FOR = User username = factory.Sequence(u'ïéàçÊÀ{0}'.format) class NonAsciiProfileFactory(ProfileFactory): """ Use this factory to create a standard user with non-ASCII characters in its username. """ FACTORY_FOR = Profile user = factory.SubFactory(NonAsciiUserFactory)
zds-member
/zds-member-0.1.5.tar.gz/zds-member-0.1.5/member/factories.py
factories.py