saving picture to mongodb

You don’t necessarily need GridFS for storing files in MongoDB, but it surely makes it a nicer experience, because it handles the splitting and saving of the binary data, while making the metadata also available. You can then store an ID in your User document to the avatar picture.

That aside, you could also store binary data directly in your documents, though in your code you are not saving the data. You simply are opening it with PIL.Image, but then doing nothing with it.

Assuming you are using pymongo for your driver, I think what you can do is just wrap the binary data in a Binary container, and then store it. This is untested by me, but I assume it should work:

from pymongo.binary import Binary

binary_avatar = Binary(avat)

user={
    ...
    "avatar":avatar,
    "avatar_file": binary_avatar
    ...
}

Now that being said… just make it easier on yourself and use GridFS. That is what it is meant for.

If you were to use GridFS, it might look like this:

from gridfs import GridFS

avat_ctype = self.request.files['avatar'][0]["content_type"]

fs = GridFS(db)
avatar_id = fs.put(avat, content_type=avat_ctype, filename=nomfich)

user={
    ...
    "avatar_name":avatar,
    "avatar_id": avatar_id
    ...
}

Leave a Comment