mongodb 学习笔记四 GridFS Example

直接贴英文,翻译不好反而影响读者,英文如下:

GridFS Example

This example shows how to use gridfs to store large binaryobjects (e.g. files) in MongoDB.

See also

The API docs for gridfs.

See also

This blog postfor some motivation behind this API.

Setup

We start by creating a GridFS instance to use:

>>> from pymongo import Connection
>>> import gridfs
>>>
>>> db = Connection().gridfs_example
>>> fs = gridfs.GridFS(db)

Every GridFS instance is created with and willoperate on a specific Database instance.

Saving and Retrieving Data

The simplest way to work with gridfs is to use its key/valueinterface (the put() andget() methods). To write data to GridFS, useput():

>>> a = fs.put("hello world")

put() creates a new file in GridFS, and returnsthe value of the file document’s "_id" key. Given that "_id"we can use get() to get back the contents of thefile:

>>> fs.get(a).read()
'hello world'

get() returns a file-like object, so we get thefile’s contents by calling read().

In addition to putting a str as a GridFS file, we can alsoput any file-like object (an object with a read()method). GridFS will handle reading the file in chunk-sized segmentsautomatically. We can also add additional attributes to the file askeyword arguments:

>>> b = fs.put(fs.get(a), filename="foo", bar="baz")
>>> out = fs.get(b)
>>> out.read()
'hello world'
>>> out.filename
u'foo'
>>> out.bar
u'baz'
>>> out.upload_date
datetime.datetime(...)

The attributes we set in put() are stored in thefile document, and retrievable after callingget(). Some attributes (like "filename") arespecial and are defined in the GridFS specification - see thatdocument for more details.

例子源码如下:

from pymongo import Connection
import gridfs
db = Connection().gridfs_example
fs = gridfs.GridFS(db)
a = fs.put("hello world")
print a
content = fs.get(a).read()
print content
b = fs.put(fs.get(a), filename="foo", bar="baz")
out = fs.get(b)
print b
print out.filename
print out.bar



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值