codec_options -- Tools for specifying BSON codec options#
Tools for specifying BSON codec options.
- class bson.codec_options.CodecOptions(document_class: Type[Mapping[str, Any]] | None = None, tz_aware: bool = False, uuid_representation: int | None = 0, unicode_decode_error_handler: str = 'strict', tzinfo: tzinfo | None = None, type_registry: TypeRegistry | None = None, datetime_conversion: DatetimeConversion | None = DatetimeConversion.DATETIME)#
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
RawBSONDocumenttype:>>> 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
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 日期时间和时区 for examples using the tz_aware and tzinfo options.
See 处理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
MutableMapping. Defaults todict.tz_aware: If
True, BSON datetimes will be decoded to timezone aware instances ofdatetime. Otherwise they will be naive. Defaults toFalse.uuid_representation: The BSON representation to use when encoding and decoding instances of
UUID. Defaults toUNSPECIFIED. New applications should consider setting this toSTANDARDfor cross language compatibility. See 处理UUID数据 for details.unicode_decode_error_handler: The error handler to apply when a Unicode-related error occurs during BSON decoding that would otherwise raise
UnicodeDecodeError. Valid options include 'strict', 'replace', 'backslashreplace', 'surrogateescape', and 'ignore'. Defaults to 'strict'.tzinfo: A
tzinfosubclass that specifies the timezone to/from whichdatetimeobjects should be encoded/decoded.type_registry: Instance of
TypeRegistryused to customize encoding and decoding behavior.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'.
在 4.0 版本发生变更: The default for uuid_representation was changed from
PYTHON_LEGACYtoUNSPECIFIED.在 3.8 版本加入: type_registry attribute.
警告
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.
- with_options(**kwargs: Any) CodecOptions#
Make 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
在 3.5 版本加入.
- class bson.codec_options.DatetimeConversion(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Options for decoding BSON datetimes.
- DATETIME = 1#
Decode a BSON UTC datetime as a
datetime.datetime.BSON UTC datetimes that cannot be represented as a
datetimewill raise anOverflowErroror aValueError.
- DATETIME_AUTO = 4#
Decode a BSON UTC datetime as a
datetime.datetimeif possible, and aDatetimeMSif not.
- DATETIME_CLAMP = 2#
Decode a BSON UTC datetime as a
datetime.datetime, clamping tominandmax.
- DATETIME_MS = 3#
Decode a BSON UTC datetime as a
DatetimeMSobject.
- class bson.codec_options.TypeCodec#
Base class for defining type codec classes which describe how a custom type can be transformed to/from one of the types
bsoncan already encode/decode.Codec classes must implement the
python_typeattribute, and thetransform_pythonmethod to support encoding, as well as thebson_typeattribute, and thetransform_bsonmethod to support decoding.See 这个 TypeCodec 等级 documentation for an example.
- class bson.codec_options.TypeDecoder#
Base class for defining type codec classes which describe how a BSON type can be transformed to a custom type.
Codec classes must implement the
bson_typeattribute, and thetransform_bsonmethod to support decoding.See 这个 TypeCodec 等级 documentation for an example.
- class bson.codec_options.TypeEncoder#
Base 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_typeattribute, and thetransform_pythonmethod to support encoding.See 这个 TypeCodec 等级 documentation for an example.
- class bson.codec_options.TypeRegistry(type_codecs: Iterable[TypeEncoder | TypeDecoder | TypeCodec] | None = None, fallback_encoder: Callable[[Any], Any] | None = None)#
Encapsulates type codecs used in encoding and / or decoding BSON, as well as the fallback encoder. Type registries cannot be modified after instantiation.
TypeRegistrycan 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 这个 TypeRegistry 等级 documentation for an example.
- Parameters:
type_codecs (optional): iterable of type codec instances. If
type_codecscontains 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-inbsontype.fallback_encoder (optional): callable that accepts a single, unencodable python value and transforms it into a type that
bsoncan encode. See 这个 fallback_encoder 可赎回的 documentation for an example.