I’m trying to create an API that spits out JSON in Flask using MongoDB.
In my controller, I have a route setup like such:
@frontend.route('/api/get_images_by_building_id/<building_id>')
def api_get_images_by_building_id(building_id):
building_images = database.get_images_by_building_id(building_id)
return building_images
in db.py imported as database, I have the following two functions:
def get_image_ids_by_building_id(self, building_id):
try:
return self.buildings.find_one(ObjectId(building_id),{"vertical_images":1})["vertical_images"]
except:
return None
This returns:
[ObjectId('506638290f536676fc004702'), ObjectId('506638290f536676fc004703'), ObjectId('506638290f536676fc004704'), ObjectId('506638290f536676fc004705'), ObjectId('506638290f536676fc004706'), ObjectId('506638290f536676fc004707'), ObjectId('506638290f536676fc004708')]
And the second function:
def get_images_by_building_id(self, building_id):
try:
image_ids = self.get_image_ids_by_building_id(building_id)
temp = self.images.find({ "_id" : { "$in" : image_ids } })
return temp
except:
return None
What are the best practices for dealing with a mongo cursor object? It causes problems because I can’t jsonify it in the controller. In the database function should I manipulate the data exactly how I want to output it or should that be done in the controller?
I tend to like to keep the request handlers as simple and thin as possible. If
json.dumpsis not good for you and you don’t like putting a bunch of format/serialization-specific code in the database module, I usually create a module calledserializers.pyfor customizing the output.As for best practices, I think it best to not put a bunch of, “I want my controller to return it exactly like this so I will put all of this specific stuff in my db module”. What if gasp you need to return something other than json (unlikely, I know)!? It would be best for the db module to return db objects (rather than custom-serialized json strings) and have a separate module that knows how to serialize the documents.