mongodb 學習筆記四 GridFS Example

來源:互聯網
上載者:User

直接貼英文,翻譯不好反而影響讀者,英文如下:

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.filenameu'foo'>>> out.baru'baz'>>> out.upload_datedatetime.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 Connectionimport gridfsdb = Connection().gridfs_examplefs = gridfs.GridFS(db)a = fs.put("hello world")print acontent = fs.get(a).read()print contentb = fs.put(fs.get(a), filename="foo", bar="baz")out = fs.get(b)print bprint out.filenameprint out.bar

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.