+\hNUdZddlmZddlZddlZddlZddlmZddl m Z m Z m Z m Z mZmZmZmZmZmZmZmZddlmZmZmZddlmZdZdd ZGd d ej<ZGd d ej<Z Gddee Z!eee e!fZ"e e ge fZ#GddZ$Gdde%ejLZ'GddeZ(e rGddeee eZ)n Gdde(Z)e)Z*de+d<ddZ,y)z(Tools for specifying BSON codec options.) annotationsN)MutableMapping) TYPE_CHECKINGAnyCallableGenericIterableMapping NamedTupleOptionalTupleTypeUnioncast)ALL_UUID_REPRESENTATIONSUUID_REPRESENTATION_NAMESUuidRepresentation) _DocumentTypeec.t|dd}|tk(S)z9Determine if a document_class is a RawBSONDocument class. _type_markerN)getattr_RAW_BSON_DOCUMENT_MARKER)document_classmarkers U/root/niggaflix-v3/playground/venv/lib/python3.12/site-packages/bson/codec_options.py_raw_document_classr/s ^^T :F . ..c\eZdZdZej ddZejddZy) 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. cy)z>rr6ceZdZdZy) TypeCodecaBase class for defining type codec classes which describe how a custom type can be transformed to/from one of the types :mod:`bson` can already encode/decode. Codec classes must implement the ``python_type`` attribute, and the ``transform_python`` method to support encoding, as well as the ``bson_type`` attribute, and the ``transform_bson`` method to support decoding. See :ref:`custom-type-type-codec` documentation for an example. N)r.r/r0r1r"rrr<r<[s rr<cdeZdZdZ d d dZed dZed dZd dZddZ ddZ y) TypeRegistryaEncapsulates type codecs used in encoding and / or decoding BSON, as well as the fallback encoder. Type registries cannot be modified after instantiation. ``TypeRegistry`` can be initialized with an iterable of type codecs, and a callable for the fallback encoder:: >>> from bson.codec_options import TypeRegistry >>> type_registry = TypeRegistry([Codec1, Codec2, Codec3, ...], ... fallback_encoder) See :ref:`custom-type-type-registry` documentation for an example. :param type_codecs: 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. :param fallback_encoder: 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. Nc Dt|xsg|_||_i|_i|_|jt |st d|z|jD]}d}t|tr6|j|d}|j|j|j<t|tr%d}|j|j|j<|rt dtjdtjdt jd|d y) Nz%fallback_encoder %r is not a callableFTzExpected an instance of z, z, or z, got z instead)list_TypeRegistry__type_codecs_fallback_encoder _encoder_map _decoder_mapcallable TypeError isinstancer _validate_type_encoderr*r%r6r:r8r.r<)r$ type_codecsfallback_encodercodecis_valid_codecs r__init__zTypeRegistry.__init__s) "+"34!1,.,.  ! ! -,- GK[ \]]'' E"N%-++E2!%7<7M7M!!%"3"34%-!%5:5I5I!!%//2!.{/C/C.DB{G[G[F\\abkbtbtauu{}B|EEMN rc|jS)z)The list of type codecs in this registry.)rAr#s rcodecszTypeRegistry.codecss!!!rc|jS)z&The fallback encoder in this registry.)rBr#s rrJzTypeRegistry.fallback_encoders%%%rcddlm}|D]:}ttt|j |s(d|d|d}t |y)Nr)_BUILT_IN_TYPESzCTypeEncoders cannot change how built-in types are encoded (encoder z transforms type ))bsonrR issubclassrr<r%rF)r$rKrRpytypeerr_msgs rrHz#TypeRegistry._validate_type_encodersV(% )F$y%0<r>msg63704/.  8""&& )  rr>c&eZdZdZdZ dZ dZ dZy)DatetimeConversionz$Options for decoding BSON datetimes.N)r.r/r0r1DATETIMEDATETIME_CLAMP DATETIME_MS DATETIME_AUTOr"rrriris3.HN K MrricTeZdZUded<ded<ded<ded<d ed <d ed <d ed<y)_BaseCodecOptionszType[Mapping[str, Any]]rbooltz_awareintuuid_representationrfunicode_decode_error_handlerOptional[datetime.tzinfo]tzinfor> type_registryOptional[DatetimeConversion]datetime_conversionN)r.r/r0__annotations__r"rrrsrss+++N"%% %%55rrsceZdZUded<ded<ded<ded<d ed <d ed <d ed< d ddZddZddZddZed dZ d!dZ d"dZ ded<ded<y)# CodecOptionszType[_DocumentType]rrtrurvrw Optional[str]rxryrzr>r{ Optional[int]r}cyr]r")clsrrurwrxrzr{r}s r__new__zCodecOptions.__new__s rc yr]r"r$kwargss r with_optionszCodecOptions.with_options rrfcyr]r"r#s r_arguments_reprzCodecOptions._arguments_reprrrcyr]r"r#s r _options_dictzCodecOptions._options_dictrrcyr]r")robjs r_makezCodecOptions._makes rcyr]r"r#s r_asdictzCodecOptions._asdictrrc yr]r"rs r_replacezCodecOptions._replacerr_sourcez Tuple[str]_fieldsN).......)rz!Type[CodecOptions[_DocumentType]]rzOptional[Type[_DocumentType]]rurtrwrrxrrzryr{Optional[TypeRegistry]r}rr,CodecOptions[_DocumentType])rrr,CodecOptions[Any]re)r,zdict[Any, Any])rz Iterable[Any]r,rr,zdict[str, Any])rrr,r) r.r/r0r~rrrr classmethodrrrr"rrrrs++  &33))##**=@ 14:=034714 2 9  "/  +8  . 2 "/ )           rrceZdZdZfdZddej dddejf d dZ d dZ d dZ d d Z dd Z xZS)rz:Encapsulates options used encoding and / or decoding BSON.c"t|y)aEncapsulates 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. :param 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`. :param 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``. :param 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. :param 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'. :param tzinfo: A :class:`~datetime.tzinfo` subclass that specifies the timezone to/from which :class:`~datetime.datetime` objects should be encoded/decoded. :param type_registry: Instance of :class:`TypeRegistry` used to customize encoding and decoding behavior. :param datetime_conversion: Specifies how UTC datetimes should be decoded within BSON. Valid options include 'datetime_ms' to return as a DatetimeMS, 'datetime' to return as a datetime.datetime and raising a ValueError for out-of-range values, 'datetime_auto' to return DatetimeMS objects when the underlying datetime is out-of-range and 'datetime_clamp' to clamp to the minimum and maximum possible datetimes. Defaults to 'datetime'. .. 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. N)superrM)r$argsrrZs rrMzCodecOptions.__init__*sd G  rNFstrictc |xst}d} t|t} | st |s tdt|tstd||tvr tdt|tstdt||>t|tjstdt||s td|xs t}t|tstd t|t j#||||||||fS#t$r*t |drt|j t} Y4wxYw) NF __origin__zydocument_class must be dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a subclass of collections.abc.MutableMappingz.tz_aware must be True or False, was: tz_aware=zGuuid_representation must be a value from bson.binary.UuidRepresentationz3unicode_decode_error_handler must be a string, not z3tzinfo must be an instance of datetime.tzinfo, not z8cannot specify tzinfo without also setting tz_aware=Truez7type_registry must be an instance of TypeRegistry, not )dictrU_MutableMappingrFhasattrrrrGrtr ValueErrorrfr^datetimerzr>tupler) rrrurwrxrzr{r} doc_class is_mappings rrzCodecOptions.__new__~s'.$IJ S' ?C "5i"@A h-"PQYPZ [\\"*BB ]:C@ I$OkJlImn!!&(//:#MdSYl^\ $%_``);\^Mm\:MdS`NaMbc=='0!'  E S9l3!+I,@,@/!RJ SsD /EEc :|jturdnt|j}tj|j |j }dj ||j||j|j|j|jS)z;Representation of the arguments used to create this object.rzdocument_class={}, tz_aware={!r}, uuid_representation={}, unicode_decode_error_handler={!r}, tzinfo={!r}, type_registry={!r}, datetime_conversion={!s}) rrreprrgetrwrYrurxrzr{r})r$document_class_repr uuid_rep_reprs rrzCodecOptions._arguments_reprs--54@S@S;T 699(($*B*BM ??Ev'MM!55KK&&,,@ rc|j|j|j|j|j|j |j dS)z7Dictionary of the arguments used to create this object.rrurwrxrzr{r}rr#s rrzCodecOptions._options_dictsI#'"5"5 MM'+'?'?040Q0Q++!%!3!3'+'?'? rcV|jjd|jdS)N(rS)rZr.rr#s rr[zCodecOptions.__repr__s*nn--.a0D0D0F/GqI Irc Z|j}|j|tdi|S)aMake 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 r")rupdater)r$roptss rrzCodecOptions.with_optionss,%%'D KK '$' 'r)rzType[CodecOptions]rz!Optional[Type[Mapping[str, Any]]]rurtrwrrxrfrzryr{rr}r|r,rrer)rrr,r)r.r/r0r1rMr UNSPECIFIEDrirnrrrr[r __classcell__)rZs@rrr'sHR lAE"1C1O1O080448@R@[@[= #= == = "/ =  +. =  . = 2= ">= = ~ 0  J (rzCodecOptions[dict[str, Any]]DEFAULT_CODEC_OPTIONScri}t|hdzD]}|dk(r |||d<||||<tdi|S)zParse BSON codec options.>rzrur{ruuidrepresentationr}rxrrwr")setr)optionsrks r_parse_codec_optionsrs[ F \ # $ $,3AJF( ) F1I #  !& !!r)rrr,rt)rrr,r)-r1 __future__rr2renumcollections.abcrrtypingrrrrr r r r r rrr bson.binaryrrr bson.typingsrrrABCr r6r<rd _Fallbackr>rvEnumrirsrrr~rr"rrrs /"  =     '/ K#''K&>#''>&  [  {K2 3 cUCZ Y Y x dii F6 6+u]+W]-C+^L((L(^7Cn3D"r