Skip to content

Instantly share code, notes, and snippets.

@codeb2cc
Created March 7, 2012 13:23
Show Gist options
  • Save codeb2cc/1993077 to your computer and use it in GitHub Desktop.
Save codeb2cc/1993077 to your computer and use it in GitHub Desktop.
Demonstration of MongDB FileField's Losing File Reference
# -*- coding:utf-8 -*-
import tempfile
import pymongo, gridfs, mongoengine
class TheDocument(mongoengine.Document):
the_file = mongoengine.FileField()
if __name__ == '__main__':
connection = pymongo.Connection('127.0.0.1', 27017)
db = connection['TestDB']
mongoengine.connect('TestDB', host='127.0.0.1', port=27017)
with tempfile.TemporaryFile() as f:
f.write("Hello World!")
f.flush()
print '==== ==== Test A: Without Initial FileField Value ==== ===='
doc_a = TheDocument()
doc_a.save()
print 'New Document: %s' % doc_a.id
# Query the document just created
doc_b = TheDocument.objects.with_id(doc_a.id)
print 'Query the same document: %s' % doc_b.id
print 'Call replace() ...'
doc_b.the_file.replace(f, filename='doc_b')
print 'After replace(), grid_id is %s' % doc_b.the_file.grid_id
doc_b.save()
print 'Save document ...'
# Query Again
doc_c = TheDocument.objects.with_id(doc_b.id)
print 'Query again: %s' % doc_c.id
print 'grid_id is %s' % doc_c.the_file.grid_id
print '\n==== ==== Test B: With Initial FileField Value ==== ===='
doc_d = TheDocument(the_file='')
doc_d.save()
print 'New Document: %s' % doc_d.id
doc_e = TheDocument.objects.with_id(doc_d.id)
print 'Query the same document: %s' % doc_e.id
print 'Call replace() ...'
doc_e.the_file.replace(f, filename='doc_e')
print 'After replace(), grid_id is %s' % doc_e.the_file.grid_id
doc_e.save()
print 'Save document ...'
doc_f = TheDocument.objects.with_id(doc_e.id)
print 'Query again: %s' % doc_f.id
print 'grid_id is %s' % doc_f.the_file.grid_id
print '\n==== ==== MongoDB GridFS File ==== ===='
grid_fs = gridfs.GridFS(db)
print grid_fs.list()
connection.drop_database('TestDB')
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment