Mongoengine 简明教程
MongoEngine - GridFS
在 MongoDB 中,使用 GridFS 规范存储大小超过 16 MB 的文件。一个文件被分成多个块,每个块的默认大小为 255KB。大块可以尽可能大。GridFS 使用两个集合,一个用于块,另一个用于元数据。
In MongoDB, the files with size larger than 16 MB are stored using GridFS specifications. A file is divided into multiple chunks each with a default size of 255KB. Large chunk may be as large as necessary. GridFS uses two collections, one for chunks and other for metadata.
如果您想访问 GridFS 存储的任何文件,而不必将整个文件加载到内存中,可以使用 GridFS。
GridFS may be used to store any file if you want to access it without having to load it entirely in the memory.
MongoEngine API 通过 FileField 对象支持 GridFS。使用此对象,可以插入和检索数据。FileField 对象的 put() 方法有助于将文件写为 Document 的一部分。
MongoEngine API supports GridFS through FileField object. Using this object, it is possible to insert and retrieve data. The FileField object’s put() method helps writing the file as a part of Document.
from mongoengine import *
con=connect('newdb')
class lang (Document):
name=StringField()
developer=StringField()
logo=FileField()
l1=lang()
l1.name='Python'
l1.developer='Van Rossum'
f=open('pylogo.png','rb')
l1.logo.put(f,content_type='image/png')
l1.save()
可以使用 Python 文件对象中的 read() 方法检索 FileField 的内容。
Contents of FileField can be retrieved by read() method of Python’s File object.
logo = l1.logo.read()
另外还有 delete() 方法,用于删除存储的文件。
There is also delete() method to delete the stored file.
l1 = lang.objects(name='Python').first()
l1.logo.delete()
l1.save()
请注意,FileField 仅将文件 ID 存储在单独的 GridFS 集合中。因此 delete() 方法不会实际删除文件。
Note that the FileField stores only the ID of file in a separate GridFS collection. Hence delete() method does not delete the file physically.
replace() 方法有助于将文件引用替换为另一个文件。
The replace() method helps in replacing reference of file with another file.
l1 = lang.objects(name='Python').first()
f=open('newlogo.png','rb')
l1.logo.replace(f,content_type='image/png')
l1.save()