如何让 pymongo 始终返回 str 而不是 unicode? [英] How can I get pymongo to always return str and not unicode?

查看:39
本文介绍了如何让 pymongo 始终返回 str 而不是 unicode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 pymongo 文档:

From the pymongo docs:

MongoDB 以 BSON 格式存储数据.BSON 字符串采用 UTF-8 编码,因此 PyMongo 必须确保它存储的任何字符串只包含有效的 UTF-8 数据.常规字符串 () > 已验证并原封不动地存储.Unicode 字符串 () 首先被编码为 UTF-8.> 我们的示例字符串在 Python shell 中表示为 u'Mike' 而不是的原因‘Mike’ 是 PyMongo 将每个 BSON 字符串解码为 Python unicode 字符串,而不是常规的字符串."

MongoDB stores data in BSON format. BSON strings are UTF-8 encoded so PyMongo must ensure that any strings it stores contain only valid UTF-8 data. Regular strings () are > validated and stored unaltered. Unicode strings () are encoded UTF-8 first. > The reason our example string is represented in the Python shell as u’Mike’ instead of ‘Mike’ is that PyMongo decodes each BSON string to a Python unicode string, not a regular str."

数据库只能存储 UTF-8 编码的字符串对我来说似乎有点傻,但是 pymongo 中的返回类型是 unicode,这意味着我必须对文档中的每个字符串做的第一件事是再次调用 encode('utf-8') 就可以了.有什么办法可以解决这个问题,即告诉 pymongo 不要给我 unicode,而是给我原始的 str ?

It seems a bit silly to me that the database can only store UTF-8 encoded strings, but the return type in pymongo is unicode, meaning the first thing I have to do with every string from the document is once again call encode('utf-8') on it. Is there some way around this, i.e. telling pymongo not to give me unicode back but just give me the raw str?

推荐答案

不,PyMongo 中没有这样的功能;从 BSON 解码的每个字符串都被解码为 UTF-8.Python 在内部将字符串表示为 UCS-2 或某种其他格式,具体取决于 Python 版本.请参阅 代码,其中 BSON 解码器提取字符串.

No, there is no such feature in PyMongo; every string decoded from BSON is decoded as UTF-8. Python represents the string internally as UCS-2 or some other format, depending on the Python version. See the code where the BSON decoder extracts a string.

在即将推出的 PyMongo 3.x 系列中,我们可能会添加功能以实现更灵活的 BSON 解码,以允许开发人员优化此类不常见的用例.

In the upcoming PyMongo 3.x series we may add features for more flexible BSON decoding to allow developers to optimize uncommon use cases like this.

这篇关于如何让 pymongo 始终返回 str 而不是 unicode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆