backend.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. """Event Man(ager) database backend
  2. Classes and functions used to manage events and attendants database.
  3. """
  4. import pymongo
  5. from bson.objectid import ObjectId
  6. class EventManDB(object):
  7. """MongoDB connector."""
  8. db = None
  9. connection = None
  10. def __init__(self, url=None, dbName='eventman'):
  11. """Initialize the instance, connecting to the database.
  12. :param url: URL of the database
  13. :type url: str (or None to connect to localhost)
  14. """
  15. self._url = url
  16. self._dbName = dbName
  17. self.connect(url)
  18. def connect(self, url=None, dbName=None):
  19. """Connect to the database.
  20. :param url: URL of the database
  21. :type url: str (or None to connect to localhost)
  22. :return: the database we're connected to
  23. :rtype: :class:`~pymongo.database.Database`
  24. """
  25. if self.db is not None:
  26. return self.db
  27. if url:
  28. self._url = url
  29. if dbName:
  30. self._dbName = dbName
  31. self.connection = pymongo.MongoClient(self._url)
  32. self.db = self.connection[self._dbName]
  33. return self.db
  34. def get(self, collection, _id):
  35. """Get a single document with the specified `_id`.
  36. :param collection: search the document in this collection
  37. :type collection: str
  38. :param _id: unique ID of the document
  39. :type _id: str or :class:`~bson.objectid.ObjectId`
  40. :return: the document with the given `_id`
  41. :rtype: dict
  42. """
  43. if not isinstance(_id, ObjectId):
  44. _id = ObjectId(_id)
  45. results = self.query(collection, {'_id': _id})
  46. return results and results[0] or {}
  47. def query(self, collection, query=None):
  48. """Get multiple documents matching a query.
  49. :param collection: search for documents in this collection
  50. :type collection: str
  51. :param query: search for documents with those attributes
  52. :type query: dict or None
  53. :return: list of matching documents
  54. :rtype: list
  55. """
  56. db = self.connect()
  57. query = query or {}
  58. if'_id' in query and not isinstance(query['_id'], ObjectId):
  59. query['_id'] = ObjectId(query['_id'])
  60. results = list(db[collection].find(query))
  61. for result in results:
  62. result['_id'] = str(result['_id'])
  63. return results
  64. def add(self, collection, data):
  65. """Insert a new document.
  66. :param collection: insert the document in this collection
  67. :type collection: str
  68. :param data: the document to store
  69. :type data: dict
  70. :return: the document, as created in the database
  71. :rtype: dict
  72. """
  73. db = self.connect()
  74. _id = db[collection].insert(data)
  75. return self.get(collection, _id)
  76. def update(self, collection, _id, data):
  77. """Update an existing document.
  78. :param collection: update a document in this collection
  79. :type collection: str
  80. :param _id: unique ID of the document to be updatd
  81. :type _id: str or :class:`~bson.objectid.ObjectId`
  82. :param data: the updated information to store
  83. :type data: dict
  84. :return: the document, after the update
  85. :rtype: dict
  86. """
  87. db = self.connect()
  88. data = data or {}
  89. if '_id' in data:
  90. del data['_id']
  91. db[collection].update({'_id': ObjectId(_id)}, {'$set': data})
  92. return self.get(collection, _id)
  93. def delete(self, collection, _id_or_query=None, force=False):
  94. """Remove one or more documents from a collection.
  95. :param collection: search the documents in this collection
  96. :type collection: str
  97. :param _id_or_query: unique ID of the document or query to match multiple documents
  98. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or dict
  99. :param force: force the deletion of all documents, when `_id_or_query` is empty
  100. :type force: bool
  101. """
  102. if not _id_or_query and not force:
  103. return
  104. db = self.connect()
  105. if not isinstance(_id_or_query, (ObjectId, dict)):
  106. _id_or_query = ObjectId(_id_or_query)
  107. db[collection].remove(_id_or_query)