o Sbw<@sJdZddlZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZmZmZddlmZmZmZdedefdefd d Zd Zd edefd dZGdddejZGdddejZGdddeeZeeeefZeegefZ ede e!efdZ"Gddde#Z$Gddde Z%Gddde%Z&e&Z'dede&fddZ(dS) z(Tools for specifying BSON codec options.N)MutableMapping) AnyCallableDictIterableMapping NamedTupleOptionalTypeTypeVarUnioncast)ALL_UUID_REPRESENTATIONSUUID_REPRESENTATION_NAMESUuidRepresentationfunc.returncCstt|SN)propertyabcabstractmethod)rr9/tmp/pip-target-onvjaxws/lib/python/bson/codec_options.py_abstractproperty)sredocument_classcCst|dd}|tkS)z9Determine if a document_class is a RawBSONDocument class.Z _type_markerN)getattr_RAW_BSON_DOCUMENT_MARKER)rmarkerrrr_raw_document_class0s rc@:eZdZdZedefddZejdedefddZ dS) TypeEncoderaPBase class for defining type codec classes which describe how a custom type can be transformed to one of the types BSON understands. Codec classes must implement the ``python_type`` attribute, and the ``transform_python`` method to support encoding. See :ref:`custom-type-type-codec` documentation for an example. rcCdS)z>> from bson.codec_options import TypeRegistry >>> type_registry = TypeRegistry([Codec1, Codec2, Codec3, ...], ... fallback_encoder) See :ref:`custom-type-type-registry` documentation for an example. :Parameters: - `type_codecs` (optional): iterable of type codec instances. If ``type_codecs`` contains multiple codecs that transform a single python or BSON type, the transformation specified by the type codec occurring last prevails. A TypeError will be raised if one or more type codecs modify the encoding behavior of a built-in :mod:`bson` type. - `fallback_encoder` (optional): callable that accepts a single, unencodable python value and transforms it into a type that :mod:`bson` can encode. See :ref:`fallback-encoder-callable` documentation for an example. N type_codecsfallback_encoderrcCst|pg|_||_i|_i|_|jdurt|std||jD]4}d}t|tr9| |d}|j |j|j <t|t rGd}|j |j|j<|sVtdtjt jtj|fq"dS)Nz%fallback_encoder %r is not a callableFTz5Expected an instance of %s, %s, or %s, got %r instead)list_TypeRegistry__type_codecs_fallback_encoder _encoder_map _decoder_mapcallable TypeError isinstancer!_validate_type_encoderr)r%r/r1r0r*r2)r$r6r7codecZis_valid_codecrrr__init__s0      zTypeRegistry.__init__rAcCs@ddlm}|D]}ttt|j|rd||f}t|qdS)Nr)_BUILT_IN_TYPESzYTypeEncoders cannot change how built-in types are encoded (encoder %s transforms type %s))ZbsonrC issubclassr r2r%r>)r$rArCZpytypeerr_msgrrrr@s z#TypeRegistry._validate_type_encodercCsd|jj|j|jfS)Nz'%s(type_codecs=%r, fallback_encoder=%r)) __class__r*r9r:r#rrr__repr__s zTypeRegistry.__repr__othercCs6t|t|s tS|j|jko|j|jko|j|jkSr)r?typeNotImplementedr<r;r:)r$rHrrr__eq__s   zTypeRegistry.__eq__)NN) r*r+r,r-r r_Codec _FallbackrBr@rGrrKrrrrr5us   r5c@sPeZdZUeeeefed<eed<e ed<eed<e e j ed<e ed<dS)_BaseCodecOptionsrtz_awareuuid_representationunicode_decode_error_handlertzinfo type_registryN)r*r+r,r rstrr__annotations__boolintr datetimerRr5rrrrrNs  rNc@seZdZdZddejdddfdeddeeee e fde dee d e d ee jd eed dfd dZd e fddZd ee e ffddZddZde d dfddZdS) CodecOptionsa Encapsulates options used encoding and / or decoding BSON. The `document_class` option is used to define a custom type for use decoding BSON documents. Access to the underlying raw BSON bytes for a document is available using the :class:`~bson.raw_bson.RawBSONDocument` type:: >>> from bson.raw_bson import RawBSONDocument >>> from bson.codec_options import CodecOptions >>> codec_options = CodecOptions(document_class=RawBSONDocument) >>> coll = db.get_collection('test', codec_options=codec_options) >>> doc = coll.find_one() >>> doc.raw '\x16\x00\x00\x00\x07_id\x00[0\x165\x91\x10\xea\x14\xe8\xc5\x8b\x93\x00' The document class can be any type that inherits from :class:`~collections.abc.MutableMapping`:: >>> class AttributeDict(dict): ... # A dict that supports attribute access. ... def __getattr__(self, key): ... return self[key] ... def __setattr__(self, key, value): ... self[key] = value ... >>> codec_options = CodecOptions(document_class=AttributeDict) >>> coll = db.get_collection('test', codec_options=codec_options) >>> doc = coll.find_one() >>> doc._id ObjectId('5b3016359110ea14e8c58b93') See :doc:`/examples/datetimes` for examples using the `tz_aware` and `tzinfo` options. See :doc:`/examples/uuid` for examples using the `uuid_representation` option. :Parameters: - `document_class`: BSON documents returned in queries will be decoded to an instance of this class. Must be a subclass of :class:`~collections.abc.MutableMapping`. Defaults to :class:`dict`. - `tz_aware`: If ``True``, BSON datetimes will be decoded to timezone aware instances of :class:`~datetime.datetime`. Otherwise they will be naive. Defaults to ``False``. - `uuid_representation`: The BSON representation to use when encoding and decoding instances of :class:`~uuid.UUID`. Defaults to :data:`~bson.binary.UuidRepresentation.UNSPECIFIED`. New applications should consider setting this to :data:`~bson.binary.UuidRepresentation.STANDARD` for cross language compatibility. See :ref:`handling-uuid-data-example` for details. - `unicode_decode_error_handler`: The error handler to apply when a Unicode-related error occurs during BSON decoding that would otherwise raise :exc:`UnicodeDecodeError`. Valid options include 'strict', 'replace', 'backslashreplace', 'surrogateescape', and 'ignore'. Defaults to 'strict'. - `tzinfo`: A :class:`~datetime.tzinfo` subclass that specifies the timezone to/from which :class:`~datetime.datetime` objects should be encoded/decoded. - `type_registry`: Instance of :class:`TypeRegistry` used to customize encoding and decoding behavior. .. versionchanged:: 4.0 The default for `uuid_representation` was changed from :const:`~bson.binary.UuidRepresentation.PYTHON_LEGACY` to :const:`~bson.binary.UuidRepresentation.UNSPECIFIED`. .. versionadded:: 3.8 `type_registry` attribute. .. warning:: Care must be taken when changing `unicode_decode_error_handler` from its default value ('strict'). The 'replace' and 'ignore' modes should not be used when documents retrieved from the server will be modified in the client application and stored back to the server. NFstrictclsrrOrPrQrRrSrc Cs|pt}d}zt|t}Wnty!t|drt|jt}Ynw|s,t|s,tdt|ts5td|t vr=t dt|t sFt d|durZt|t j sTtd|sZt d|p^t}t|tshtd t|||||||fS) NF __origin__zydocument_class must be dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a subclass of collections.abc.MutableMappingztz_aware must be True or FalsezGuuid_representation must be a value from bson.binary.UuidRepresentationz-unicode_decode_error_handler must be a stringz-tzinfo must be an instance of datetime.tzinfoz8cannot specify tzinfo without also setting tz_aware=Truez1type_registry must be an instance of TypeRegistry)dictrD_MutableMappingr>hasattrr\rr?rVr ValueErrorrTrXrRr5tuple__new__) r[rrOrPrQrRrSZ doc_classZ is_mappingrrrrbsN          zCodecOptions.__new__cCsD|jturdnt|j}t|j|j}d||j||j|j|j fS)z;Representation of the arguments used to create this object.r]ztdocument_class=%s, tz_aware=%r, uuid_representation=%s, unicode_decode_error_handler=%r, tzinfo=%r, type_registry=%r) rr]reprrgetrPrOrQrRrS)r$Zdocument_class_reprZ uuid_rep_reprrrr_arguments_reprVszCodecOptions._arguments_reprcCs|j|j|j|j|j|jdS)z7Dictionary of the arguments used to create this object.rrOrPrQrRrSrfr#rrr _options_dictlszCodecOptions._options_dictcCsd|jj|fS)Nz%s(%s))rFr*rer#rrrrGxszCodecOptions.__repr__kwargscKs |}||tdi|S)ahMake a copy of this CodecOptions, overriding some options:: >>> from bson.codec_options import DEFAULT_CODEC_OPTIONS >>> DEFAULT_CODEC_OPTIONS.tz_aware False >>> options = DEFAULT_CODEC_OPTIONS.with_options(tz_aware=True) >>> options.tz_aware True .. versionadded:: 3.5 Nr)rgupdaterY)r$rhoptsrrr with_options{s zCodecOptions.with_options)r*r+r,r-rZ UNSPECIFIEDr r rrTrrVrWrXrRr5rbrerrgrGrkrrrrrYs:N 7 rYoptionscCsJi}t|hd@D]}|dkr|||d<q ||||<q tdi|S)zParse BSON codec options.>rrRrQuuidrepresentationrSrOrmrPNr)setrY)rlrhkrrr_parse_codec_optionss rp))r-rrXcollections.abcrr^typingrrrrrrr r r r r Z bson.binaryrrrrrrrVrABCr!r/r2rLrMrTr3objectr5rNrYZDEFAULT_CODEC_OPTIONSrprrrrs* 4T ;