Pymongo BSON Binary save and retrieve?

时光总嘲笑我的痴心妄想 提交于 2019-12-01 22:34:22

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().

  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.

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:

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

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

>>> 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])

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

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'}

BSON.decode(gotfield)

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

BSON.decode(bson.BSON(gotfield))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!