python mongodb 存储文档 pdf_python-mongodb存储文件

本文介绍了如何使用Python 2.7和MongoDB 2.6.5存储和检索文件,包括直接存储二进制数据和使用GridFS。对于小文件,可以直接将文件内容转换为二进制数据存入MongoDB,而对于大文件,推荐使用GridFS,它将文件分块存储,支持MongoDB的分片和复制机制。示例代码中展示了存储、获取、删除和列出文件名的操作。
摘要由CSDN通过智能技术生成

python 版本为2.7

mongodb版本2.6.5

使用mongodb存储文件,可以使用两种方式,一种是像存储普通数据那样,将文件转化为二进制数据存入mongodb,另一种使用gridfs,咱们先来说说第一种

先读取文件内容,然后塞进bson.binary.Binary对象里,最后像平常那样写入数据库,是不是很简单呢,获取文件一样的简单,像平时那样查找数据,然后将二进制内容写入文件即可

#coding=utf-8

'''

Created on 2015-10-8

@author: kwsy2015

'''

import pymongo

import bson.binary

from pymongo import MongoClient

from cStringIO import StringIO

def insertFile():

client = MongoClient('localhost', 27017)

#获得一个database

db = client.MongoFile

#获得一个collection

coll = db.image

filename = 'F:/测试数据/hehe.jpg'.decode('utf-8')

with open (filename,'rb') as myimage:

content = StringIO(myimage.read())

coll.save(dict(

content= bson.binary.Binary(content.getvalue()),

filename = 'hehe.jpg'

))

def getFile():

client = MongoClient('localhost', 27017)

#获得一个database

db = client.MongoFile

#获得一个collection

coll = db.image

data = coll.find_one({'filename':'hehe.jpg'})

out = open('F:/测试数据/test4.jpg'.decode('utf-8'),'wb')

out.write(data['content'])

out.close()

getFile()

因为我的文件路径都带有中文,因此需要用utf-8解码,否则会报错的

使用上述方法存储小文件是很方便的,那么如果是大文件呢,可以使用gridfs

gridfs会把文件分成若干块来存储,每一块的大小默认为256K,所以,如果是小文件,就不要用gridfs来存储了,不然会浪费空间的,gridfs是MongoDB之上的分布式文件系统,可以使用mongodb的分片和复制机制,因为Mongodb分配数据空间时以2GB为单位,所以gridfs不产生磁盘碎片。

#coding=utf-8

'''

Created on 2015-9-29

@author: Administrator

'''

from pymongo import MongoClient

from bson.objectid import ObjectId

from gridfs import *

def insertFile():

client = MongoClient('localhost', 27017)

db = client.Pic

fs = GridFS(db, 'images')

with open ('F:/测试数据/hehe.jpg'.decode('utf-8'),'rb') as myimage:

data=myimage.read()

id = fs.put(data,filename='first')

print id

def getFile():

client = MongoClient('localhost', 27017)

db = client.Pic

fs = GridFS(db, 'images')

file = fs.get_version('first', 0)

data = file.read()

out = open('F:/测试数据/test3.jpg'.decode('utf-8'),'wb')

out.write(data)

out.close()

def delFile():

client = MongoClient('localhost', 27017)

db = client.Pic

fs = GridFS(db, 'images')

fs.delete(ObjectId('560a531b0d4eae34a4edbfdd'))

def listName():

client = MongoClient('localhost', 27017)

db = client.Pic

fs = GridFS(db, 'images')

print fs.list()

listName()

写入文件时,我们可以设置它的filename,如果多个文件使用同一个filename呢,我们在获取文件时可以使用get_version()函数,第一个参数是filename,第二个参数是版本,从0开始。

此外,我们还可以使用get(),函数,需传入文件的ObjectId

使用python操作gridfs总得来说是很方便的,毕竟所提供的函数就那么几个,稍微用心看看源码就没问题了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值