From d477e3e6c89eea0ab7dc7bff3c25d33b9976c69c Mon Sep 17 00:00:00 2001 From: David Lai Date: Mon, 7 Jun 2021 23:23:26 +0800 Subject: [PATCH] support insert bytes without bson --- montydb/types/_bson.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/montydb/types/_bson.py b/montydb/types/_bson.py index 681a79d..e265308 100644 --- a/montydb/types/_bson.py +++ b/montydb/types/_bson.py @@ -1,5 +1,6 @@ import sys import types +import base64 class BSON_(types.ModuleType): @@ -204,6 +205,10 @@ def default(self, obj): if isinstance(obj, NoBSON.ObjectId): return {"$oid": str(obj)} + if isinstance(obj, bytes): + return {"$binary": {"base64": base64.b64encode(obj).decode(), + "subType": "00"}} + if isinstance(obj, NoBSON.datetime.datetime): millis = NoBSON._datetime_to_millis(obj) return {"$date": millis} @@ -252,6 +257,8 @@ def document_encode(cls, doc, check_keys=False, *args, **kwargs): def object_hook(cls, obj, opts=DEFAULT_CODEC_OPTIONS): if "$oid" in obj: return cls.ObjectId(obj["$oid"]) + if "$binary" in obj: + return base64.b64decode(obj["$binary"]["base64"]) if "$date" in obj: return cls._millis_to_datetime(int(obj["$date"]), opts) if "$regex" in obj: