草庐IT

Python bson 库 : get bson alias

coder 2023-10-31 原文

我正在寻找如下所示的 type_of 方法:

import bson
bson.type_of(42)  # it should return "int".
bson.type_of("hello")  # it should return "string".
type("hello").__name__   # it returns "str" and not "string" therefore no suitable.

我想要的结果(intstring)是 BSON 别名(参见 https://docs.mongodb.com/manual/reference/bson-types/)。

这个方法type_of是否已经存在?

如果它返回类型的数字(1 表示 Double,2 表示 String ...)就可以了。

谢谢,

编辑: 这是我目前的解决方案:

type_of = {
    type(2.5).__name__: "number",
    type(1).__name__: "number",
    type("a_string").__name__: "string",
    type([1, 2]).__name__: "array",
    type(True).__name__: "bool"
}  # type_of[type(3).__name__] returns "number"

最佳答案

如果您想要实际的 BSON 类型(数字不是 bson 类型),我不确定是否有办法。我已经使用这个函数来帮助理清 python 将对象编码为:

def what_bson_type(input):
    import bson
    return bson._ELEMENT_GETTER[bson.BSON.encode({"t":input})[4]].__name__[5:]

注意:这些“类型”与 bson 规范不匹配,但它们在过去足以帮助我。

>>> what_bson_type("hi")
'string'
>>> what_bson_type(1)
'int'
>>> what_bson_type(sys.maxint)
'int64'
>>> what_bson_type(True)
'boolean'
>>> what_bson_type({"a":"b"})
'object'
>>> what_bson_type(1.2)
'float'
>>> what_bson_type([1,2])
'array'
>>> what_bson_type(re.compile(r".*"))
'regex'
>>> what_bson_type(bson.Binary("hi"))
'binary'

关于Python bson 库 : get bson alias,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41959847/

有关Python bson 库 : get bson alias的更多相关文章

随机推荐