Question

Edit: using python 2.7 on Windows 7

I'm having trouble persisting data in a FileField using mongoengine. The file size before & after saving is drastically different. Running this:

from mongoengine import *
class Test(Document):

   File = FileField()

#connect to my mongodb
connect( 'myDB', host= '192.168.0.3' )

Test.drop_collection()

# write to mongodb GridFS, per the mongoengine documentation: https://mongoengine-odm.readthedocs.org/en/latest/guide/gridfs.html
test = Test()
test.File.put( open( r'c:\temp\owl.jpg', 'r') )
test.save()

#get the Test instance from the db, print out the number of bytes according to mongoengine
test = Test.objects().first()
print test.File.length

#just to make sure we aren't crazy, check the filesize on disk:
print os.path.getsize( r'c:\temp\owl.jpg' )

Generates this output:

864
145047

Any pointers would be appreciated!

Was it helpful?

Solution

Changing:

test.File.put( open( r'c:\temp\owl.jpg', 'r') )

to:

test.File.put( open( r'c:\temp\owl.jpg', 'rb') )

Fixes the problem. Too bad the behavior is inconsistent between OS's.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top