codec_options – Tools for specifying BSON codec options

Tools for specifying BSON codec options.

  • class bson.codec_options.CodecOptions
  • Encapsulates options used encoding and / or decoding BSON.

The document_class option is used to define a custom type for usedecoding BSON documents. Access to the underlying raw BSON bytes fora document is available using the RawBSONDocumenttype:

  1. >>> from bson.raw_bson import RawBSONDocument
  2. >>> from bson.codec_options import CodecOptions
  3. >>> codec_options = CodecOptions(document_class=RawBSONDocument)
  4. >>> coll = db.get_collection('test', codec_options=codec_options)
  5. >>> doc = coll.find_one()
  6. >>> doc.raw
  7. '\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 fromMutableMapping:

  1. >>> class AttributeDict(dict):
  2. ... # A dict that supports attribute access.
  3. ... def __getattr__(self, key):
  4. ... return self[key]
  5. ... def __setattr__(self, key, value):
  6. ... self[key] = value
  7. ...
  8. >>> codec_options = CodecOptions(document_class=AttributeDict)
  9. >>> coll = db.get_collection('test', codec_options=codec_options)
  10. >>> doc = coll.find_one()
  11. >>> doc._id
  12. ObjectId('5b3016359110ea14e8c58b93')

See Datetimes and Timezones for examples using the tz_aware andtzinfo options.

See UUIDLegacy for examples using theuuid_representation option.

Parameters:

  • document_class: BSON documents returned in queries will be decodedto an instance of this class. Must be a subclass ofMutableMapping. Defaults to dict.
  • tz_aware: If True, BSON datetimes will be decoded to timezoneaware instances of datetime. Otherwise they will benaive. Defaults to False.
  • uuid_representation: The BSON representation to use when encodingand decoding instances of UUID. Defaults toPYTHON_LEGACY.
  • unicode_decode_error_handler: The error handler to apply whena Unicode-related error occurs during BSON decoding that wouldotherwise raise UnicodeDecodeError. Valid options include‘strict’, ‘replace’, and ‘ignore’. Defaults to ‘strict’.
  • tzinfo: A tzinfo subclass that specifies thetimezone to/from which datetime objects should beencoded/decoded.
  • type_registry: Instance of TypeRegistry used to customizeencoding and decoding behavior.

New in version 3.8: type_registry attribute.

Warning

Care must be taken when changingunicode_decode_error_handler from its default value (‘strict’).The ‘replace’ and ‘ignore’ modes should not be used when documentsretrieved from the server will be modified in the client applicationand stored back to the server.

  • withoptions(**kwargs_)
  • Make a copy of this CodecOptions, overriding some options:
  1. >>> from bson.codec_options import DEFAULT_CODEC_OPTIONS
  2. >>> DEFAULT_CODEC_OPTIONS.tz_aware
  3. False
  4. >>> options = DEFAULT_CODEC_OPTIONS.with_options(tz_aware=True)
  5. >>> options.tz_aware
  6. True

New in version 3.5.

  • class bson.codec_options.TypeCodec
  • Base class for defining type codec classes which describe how acustom type can be transformed to/from one of the types bsoncan already encode/decode.

Codec classes must implement the python_type attribute, and thetransform_python method to support encoding, as well as thebson_type attribute, and the transform_bson method to supportdecoding.

See The TypeCodec Class documentation for an example.

  • class bson.codec_options.TypeDecoder
  • Base class for defining type codec classes which describe how aBSON type can be transformed to a custom type.

Codec classes must implement the bson_type attribute, and thetransform_bson method to support decoding.

See The TypeCodec Class documentation for an example.

  • bson_type
  • The BSON type to be converted into our own type.

  • transformbson(_value)

  • Convert the given BSON value into our own type.
  • class bson.codec_options.TypeEncoder
  • Base class for defining type codec classes which describe how acustom type can be transformed to one of the types BSON understands.

Codec classes must implement the python_type attribute, and thetransform_python method to support encoding.

See The TypeCodec Class documentation for an example.

  • python_type
  • The Python type to be converted into something serializable.

  • transformpython(_value)

  • Convert the given Python object into something serializable.
  • class bson.codecoptions.TypeRegistry(_type_codecs=None, fallback_encoder=None)
  • Encapsulates type codecs used in encoding and / or decoding BSON, aswell as the fallback encoder. Type registries cannot be modified afterinstantiation.

TypeRegistry can be initialized with an iterable of type codecs, anda callable for the fallback encoder:

  1. >>> from bson.codec_options import TypeRegistry
  2. >>> type_registry = TypeRegistry([Codec1, Codec2, Codec3, ...],
  3. ... fallback_encoder)

See The TypeRegistry Class documentation for an example.

Parameters:

  • type_codecs (optional): iterable of type codec instances. Iftype_codecs contains multiple codecs that transform a singlepython or BSON type, the transformation specified by the type codecoccurring last prevails. A TypeError will be raised if one or moretype codecs modify the encoding behavior of a built-in bsontype.
  • fallback_encoder (optional): callable that accepts a single,unencodable python value and transforms it into a type thatbson can encode. See The fallback_encoder Callabledocumentation for an example.