MongoEngine – 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 may be used to store any file if you want to access it without having to load it entirely in the memory.
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()
Contents of FileField can be retrieved by read() method of Python’s File object.
logo = l1.logo.read()
There is also delete() method to delete the stored file.
l1 = lang.objects(name=''Python'').first() l1.logo.delete() l1.save()
Note that the FileField stores only the ID of file in a separate GridFS collection. Hence delete() method does not delete the file physically.
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()
”;