agronholm/mongo-python-driver-py3k — Issue #5: Can't write to GridFS file?
Author: e1ven
Created: 2011-12-27 20:26:41+00:00
State: open

I'm trying to copy files into gridFS, with code that worked under Python2.6, but seems to be blowing up under python3.
It's entirely possible that I'm doing something wrong, but I'd appreciate any advice in finding it-

The snippet which is complaining tries to open a file (as specified by string fullpath), hash it, then copy it into GridFS with a filename that equals that SHA.

#Hash the file in chunks
SHA512 = hashlib.sha512()
File = open(fullpath, 'rb')
while True:
buf = File.read(0x100000)
if not buf:
break
SHA512.update(buf)
File.close()
digest = SHA512.hexdigest()
print("Opening File " + fullpath + " as digest " + digest)
if not server.bin_GridFS.exists(filename=digest):
with open(fullpath) as localfile:
oid = server.bin_GridFS.put(localfile,filename=digest, content_type=client_filetype)
stored = True
else:
stored = True

I get the following traceback-

Traceback (most recent call last):
File "/usr/local/lib/python3.2/dist-packages/tornado-2.1.1-py3.2.egg/tornado/web.py", line 954, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "./webfront.py", line 790, in post
oid = server.bin_GridFS.put(localfile,filename=digest, content_type=client_filetype)
File "/usr/local/lib/python3.2/dist-packages/pymongo3-1.9b1-py3.2-linux-i686.egg/gridfs/__init__.py", line 114, in put
grid_file.write(data)
File "/usr/local/lib/python3.2/dist-packages/pymongo3-1.9b1-py3.2-linux-i686.egg/gridfs/grid_file.py", line 254, in write
to_write = data.read(self.chunk_size)
File "/usr/lib/python3.2/codecs.py", line 300, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0: invalid start byte
ERROR:root:500 POST /uploadnewmessage (127.0.0.1) 51.73ms