热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PymongoBSON二进制文件保存和检索?-PymongoBSONBinarysaveandretrieve?

ImworkinginPythonwithMongoDBtryingtosaveanarrayoffloatstightly.我在Python中工作,MongoDB试图保

I'm working in Python with MongoDB trying to save an array of floats tightly.

我在Python中工作,MongoDB试图保存一个浮点数组。

I can Create and store correctly *

我可以正确地创建和存储*。

but I CANNOT RETRIEVE THE DATA IN A USABLE FORMAT.

但是我不能以可用的格式检索数据。

>>> import random, array, pymongo
>>> from bson.binary import Binary as BsonBinary
>>> con = pymongo.Connection('localhost', 27017)
>>> mm = con['testDatabase']
>>> vals = [random.random() *100 for x in range(1, 5)]
>>> vals
[2.9962593, 64.5582810776, 32.3781311717, 82.0606953423]
>>> varray = array.array('f', vals)
>>> varray
array('f', [2.9962593, 64.5582810776, 32.3781311717, 82.0606953423])
>>> vstring = varray.tostring()
>>> vstring
'\xb7\xc2?@\xd7\x1d\x81B5\x83\x01B\x13\x1f\xa4B'
>>> vbson = BsonBinary(vstring, 5)
>>> vbson
Binary('\xb7\xc2?@\xd7\x1d\x81B5\x83\x01B\x13\x1f\xa4B', 5)
>>> doc1 = { 'something': 1 , 'else' : vbson}
>>> doc1
{'something': 1, 'else': Binary('\xb7\xc2?@\xd7\x1d\x81B5\x83\x01B\x13\x1f\xa4B', 5)}
>>> mm.test1.insert(doc1)
ObjectID('530f7af1d809d80d3db1f635')
>>> gotdoc = mm.test1.find_one()
>>> gotdoc
{u'_id': ObjectId('530f7af1d809d80d3db1f635'), u'something': 3, u'else': Binary('\xb7\xc2?@\xd7\x1d\x81B5\x83\x01B\x13\x1f\xa4B', 5)}
>>> gotfield = gotdoc['else']
>>> gotfield
Binary('\xb7\xc2?@\xd7\x1d\x81B5\x83\x01B\x13\x1f\xa4B', 5)
>>> from bson import BSON
>>> BSON.decode(gotfield)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unbound method decode() must be called with BSON instance as first argument (got Binary instance instead)
>>> gotfield.decode()
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 0: ordinal not in range(128)
>>>

Once I get my Python string back, I can get my array of random floats back. But how?

一旦我取回我的Python字符串,我就可以得到我的随机浮动的数组。但如何?

5 个解决方案

#1


3  

Let's go through the errors:

让我们来看看这些错误:

  1. The first error appears simply because you need an actual BSON object. Note, that you have never encoded any data - creating bson.binary.Binary object does not mean invoking BSON.encode().

    第一个错误看起来很简单,因为您需要一个实际的BSON对象。注意,您从未对任何数据进行编码——创建bson.binary。二进制对象并不意味着调用BSON.encode()。

  2. And that is where PyMongo cheats you a bit. The bson.binary.Binary is a runtime-patched str or bytes instance (see source). That is why you get the second error: what you call is actually str.decode(), not BSON.decode(). So, gotfield contains the random float data you've stored initially, but the object itself has some different methods (e.g. repr()) bound to it.

    这就是PyMongo欺骗你的地方。bson.binary。二进制是一个runtime-patched str或bytes实例(参见源代码)。这就是为什么你会得到第二个错误:你所调用的实际上是str.decode(),而不是BSON.decode()。因此,gotfield包含您最初存储的随机浮动数据,但是对象本身有一些不同的方法(例如repr())绑定到它。

#2


2  

I'm coming~ I just find a way. Hope this may help you somehow.

我来了~我只是想办法。希望这对你有帮助。

from cStringIO import StringIO
from PIL import Image

save image:

保存图片:

cOntent= StringIO(f.read())

c = dict(
    cOntent=bson.binary.Binary(content.getvalue()),
)
# insert dict into my database, sha1 is primary key
image_data[sha1] = c

retrieve image:

检索图片:

f = image_data[sha1]
image = Image.open(StringIO(f['content']))

----EDIT----

- - - - -编辑- - - - -

If you want to return an image from web servers.Do like this:

如果您想要从web服务器返回图像。这样做:

f = image_data[sha1]
# f['mime'] is the type of image, for example 'png'.
resp = Response(f['content'], mimetype='image/' + f['mime'])
return resp

#3


1  

Use array.fromstring for the final decoding stage. I can get to the same spot you're at like so:

使用array.fromstring作为最终的解码阶段。我可以到你所在的地方去:

>>> from bson import Binary
>>> import array
>>> gotstring = Binary('\xb7\xc2?@\xd7\x1d\x81B5\x83\x01B\x13\x1f\xa4B', 5)

And finally:

最后:

>>> a = array.array('f')
>>> a.fromstring(gotstring)
>>> a
array('f', [2.9962594509124756, 64.55828094482422, 32.37813186645508, 82.0606918334961])

#4


0  

You need to encode the array before storing it, and should not use the array.tostring. Please have a look at the documentation here.

您需要在存储该数组之前对其进行编码,并且不应该使用array.tostring。请看这里的文档。

from bson import BSON
bson_string = BSON.encode({"hello": "world"})
>>> bson_string
'\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00'
>>> bson_string.decode()
{u'hello': u'world'}

#5


0  

BSON.decode(gotfield)

BSON.decode(gotfield)

it has a TypeError problem,and you should write it like that below

它有一个类型错误的问题,你应该像下面这样写。

BSON.decode(bson.BSON(gotfield))

BSON.decode(bson.BSON(gotfield))


推荐阅读
author-avatar
百变精灵2596
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有