【问题标题】:What data 'structure' does fs.get_last_version return?fs.get_last_version 返回什么数据“结构”?
【发布时间】:2014-02-08 09:23:52
【问题描述】:

当我使用get_last_version 从数据库中获取图像时,实际返回的是什么,即一个数组,构成文件的所有块的合并二进制数据(作为字符串),还是其他什么?

dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
filename = "my_image.jpg"
my_image_file = fs.get_last_version(filename=filename)

我想用 base64 编码 my_image_file

import base64

encoded_img_file = base64.b64encode(my_image_file)
return encoded_img_file

但我收到 500 错误。

我无法从文档中收集使用 get_last_version 时实际返回的内容:

http://api.mongodb.org/python/current/api/gridfs/#gridfs.GridFS.get_last_version

更多研究:

我遵循了这篇文章的逻辑:

http://blog.pythonisito.com/2012/05/gridfs-mongodb-filesystem.html

在服务器上运行 Python 的 shell 中可以看到返回了 Binary() - 那么我是否应该能够按照上面的演示进行 base64 编码?:

>>> import pymongo
>>> import gridfs
>>> import os
>>> hostname = os.environ['OPENSHIFT_MONGODB_DB_URL']
>>> conn = pymongo.MongoClient(host=hostname)
>>> db = conn.grid_files
>>> fs = gridfs.GridFS(db)
>>> list(db.fs.chunks.find())

[{u'files_id': ObjectId('52db4d9e70914413718f2ec4'), u'_id': ObjectId('52db4d9e7
0914413718f2ec5'), u'data': Binary('lots of binary code', 0), u'n': 0}]

【问题讨论】:

    标签: python-2.7 pymongo bottle gridfs


    【解决方案1】:

    除非有更好的答案,否则这就是我想出的。

    get_last_version 返回一个Binary() 对象。

    关于 base64 编码和返回,我是这样做的:

    dbname = 'grid_files'
    db = connection[dbname]
    fs = gridfs.GridFS(db)
    filename = "my_image.jpg"
    my_image_file = fs.get_last_version(filename=filename)
    encoded_img_file = base64.b64encode(my_image_file.read())
    return encoded_img_file
    

    然后在前端访问它:

    $("#my_img").attr("src", "data:image/png;base64," + data);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2016-06-28
      • 1970-01-01
      • 2011-03-21
      相关资源
      最近更新 更多