python - 将图像存储在 MongoDB 中

标签 python mongodb pymongo gridfs

我使用 PyMongo 连接到我的数据库,当用户上传图像时,我想使用 GridFS 将其存储在集合中的用户特定文档中。我这样做是这样的:

class uploadHandler(BaseHandler):

@tornado.web.authenticated

def get(self):

    self.render("upload.html",user=self.current_user)

def post(self):
    db = pymongo.Connection('mongodb://heroku_app.mongolab.com:/heroku_app').heroku_appxxxx
    user = db.userInfo.find_one({'Username':self.current_user})
    file1 = self.request.files['images'][0]
    original_fname = file1['filename']

    print "file: " + original_fname + " is uploaded"

    fs = gridfs.GridFS(user)
    fs.put(file1)
    #db.userInfo.update({'Username':self.current_user},{'$push':{'Images': file1}})  

    self.redirect('/upload')

但这给了我错误:

  Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\tornado\web.py", line 1332, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "C:\Users\rsaxs\workspace\pie\src\Server.py", line 4101, in post
    fs = gridfs.GridFS(user)
  File "C:\Python27\lib\site-packages\gridfs\__init__.py", line 53, in __init__
    raise TypeError("database must be an instance of Database")
TypeError: database must be an instance of Database

如何才能最好地将图像存储在集合中特定文档中的 mongoDB 中?

最佳答案

GridFS您可以保存和读取超过 BSON 文档文件大小限制 (16 MB) 的文件。它通常用于存储媒体,因为您可以将数据流式传输到客户端。

GridFS 有一个特定的文档结构——它实际上由多个文档组成,只需在向 GridFS 插入内容时在 db 中检查它即可。由于它具有特殊的结构,并且文件可能会超过 16MB 文档大小限制,因此您不能在其他文档中包含 GridFS 文档。

如果您想引用某些 GridFS 对象,可以通过保存特定 GridFS 文件的 file_id 并在需要检索其内容时查询该文件。

关于python - 将图像存储在 MongoDB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28327746/

相关文章:

python - 将 None 传递给参数是否正确?

mongodb - Windows 10 Pro 的 Cassandra 和 MongoDB 最低系统要求

ruby-on-rails - Rails 3 + rails_admin + MongoDB 如何表示数组

mongodb - 从子文档数组中删除数组元素

python - mongoengine - 使用管道查找两个数组之间的匹配项

Pymongo:在 Response 中删除 $oid 的最佳方法

python - 使用 Ctrl+C 停止 Python Gtk.Application

python - 我可以使用 AES I.V.或随机数作为密码盐?

python - 在Python中检查时间是否位于开始时间和结束时间之间的最有效方法

ruby - 如何在 irb 中抑制 mongod 心跳输出