2016-05-06 12:04:22 +02:00
|
|
|
"""Utility functions for MongoDB stuff."""
|
|
|
|
|
|
|
|
from bson import ObjectId
|
|
|
|
from flask import current_app
|
|
|
|
from werkzeug.exceptions import NotFound
|
|
|
|
|
|
|
|
|
2016-07-13 16:52:48 +02:00
|
|
|
def find_one_or_404(collection_name, object_id,
|
|
|
|
projection=None):
|
2016-05-06 12:04:22 +02:00
|
|
|
"""Returns the found object from the collection, or raises a NotFound exception.
|
|
|
|
|
|
|
|
:param collection_name: name of the collection, such as 'users' or 'files'
|
|
|
|
:type collection_name: str
|
|
|
|
:param object_id: ID of the object to find.
|
|
|
|
:type object_id: str or bson.ObjectId
|
|
|
|
:returns: the found object
|
|
|
|
:rtype: dict
|
|
|
|
|
|
|
|
:raises: werkzeug.exceptions.NotFound
|
|
|
|
"""
|
|
|
|
|
|
|
|
collection = current_app.data.driver.db[collection_name]
|
2016-07-13 16:52:48 +02:00
|
|
|
found = collection.find_one(ObjectId(object_id),
|
|
|
|
projection=projection)
|
2016-05-06 12:04:22 +02:00
|
|
|
|
|
|
|
if found is None:
|
|
|
|
raise NotFound()
|
|
|
|
|
|
|
|
return found
|