0

I'm building a flask application where I will be serving small images. These images are stored in MongoDB as BinaryData. In a helper function, I can store the data with these lines of python:

    a = {"file_name": f, "payload": Binary(article.read())}
    ARTICLES.insert(a)

I'm trying to build a class that contains the image. However, I cannot find the correct field declaration

class BinaryFile(mongo.Document):
    created_at = mongo.DateTimeField(default=datetime.datetime.now, required=True)
    file_name = mongo.StringField(max_length=255, required=True)
    payload = mongo.Binary()

producing this error:

AttributeError: 'MongoEngine' object has no attribute 'Binary'

Can anyone suggest the correct way to declare this value or am I completely off base? This page does not provide a way to declare a field as Binary: http://api.mongodb.org/python/current/api/bson/index.html

Thanks!

Brian Dolan
  • 3,086
  • 2
  • 24
  • 35
  • 1
    you may be missing something simple along the lines of "from pymongo.binary import Binary". Look for something similar w Mongoengine library. And check out the Q along the lines of http://stackoverflow.com/questions/11915770/saving-picture-to-mongodb – Gabe Rainbow Jan 31 '15 at 08:19

1 Answers1

0

Gabe helped get me on the right path.

First, I had to decide whether to use standard Binary format or move to GridFS, I chose to stick with regular Binary.

What I didn't understand was that the DateTimeField and StringField were being provided by MongoEngine. Gabe's comment got me going that way and I found the MongoEngine fields docs: http://docs.mongoengine.org/apireference.html#fields

I called that and got the error here: mongoengine.fields.ImproperlyConfigured: PIL library was not found which was fixed by doing

pip install Pillow

So now I have

import datetime
from app import mongo
from flask import url_for
from bson.binary import Binary

class BinaryFile(mongo.Document):
    created_at = mongo.DateTimeField(default=datetime.datetime.now, required=True)
    file_name = mongo.StringField(max_length=255, required=True)
    payload = mongo.ImageField(required=False)

and I'm on to the next error! See you soon!

Mathieu Dhondt
  • 8,405
  • 5
  • 37
  • 58
Brian Dolan
  • 3,086
  • 2
  • 24
  • 35