backend.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. """Event Man(ager) database backend
  2. Classes and functions used to manage events and attendees database.
  3. Copyright 2015 Davide Alberani <da@erlug.linux.it>
  4. RaspiBO <info@raspibo.org>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. """
  14. import pymongo
  15. from bson.objectid import ObjectId
  16. class EventManDB(object):
  17. """MongoDB connector."""
  18. db = None
  19. connection = None
  20. def __init__(self, url=None, dbName='eventman'):
  21. """Initialize the instance, connecting to the database.
  22. :param url: URL of the database
  23. :type url: str (or None to connect to localhost)
  24. """
  25. self._url = url
  26. self._dbName = dbName
  27. self.connect(url)
  28. def connect(self, url=None, dbName=None):
  29. """Connect to the database.
  30. :param url: URL of the database
  31. :type url: str (or None to connect to localhost)
  32. :return: the database we're connected to
  33. :rtype: :class:`~pymongo.database.Database`
  34. """
  35. if self.db is not None:
  36. return self.db
  37. if url:
  38. self._url = url
  39. if dbName:
  40. self._dbName = dbName
  41. self.connection = pymongo.MongoClient(self._url)
  42. self.db = self.connection[self._dbName]
  43. return self.db
  44. def get(self, collection, _id):
  45. """Get a single document with the specified `_id`.
  46. :param collection: search the document in this collection
  47. :type collection: str
  48. :param _id: unique ID of the document
  49. :type _id: str or :class:`~bson.objectid.ObjectId`
  50. :return: the document with the given `_id`
  51. :rtype: dict
  52. """
  53. if not isinstance(_id, ObjectId):
  54. _id = ObjectId(_id)
  55. results = self.query(collection, {'_id': _id})
  56. return results and results[0] or {}
  57. def query(self, collection, query=None):
  58. """Get multiple documents matching a query.
  59. :param collection: search for documents in this collection
  60. :type collection: str
  61. :param query: search for documents with those attributes
  62. :type query: dict or None
  63. :return: list of matching documents
  64. :rtype: list
  65. """
  66. db = self.connect()
  67. query = query or {}
  68. if'_id' in query and not isinstance(query['_id'], ObjectId):
  69. query['_id'] = ObjectId(query['_id'])
  70. results = list(db[collection].find(query))
  71. for result in results:
  72. result['_id'] = str(result['_id'])
  73. return results
  74. def add(self, collection, data):
  75. """Insert a new document.
  76. :param collection: insert the document in this collection
  77. :type collection: str
  78. :param data: the document to store
  79. :type data: dict
  80. :return: the document, as created in the database
  81. :rtype: dict
  82. """
  83. db = self.connect()
  84. _id = db[collection].insert(data)
  85. return self.get(collection, _id)
  86. def update(self, collection, _id, data):
  87. """Update an existing document.
  88. :param collection: update a document in this collection
  89. :type collection: str
  90. :param _id: unique ID of the document to be updatd
  91. :type _id: str or :class:`~bson.objectid.ObjectId`
  92. :param data: the updated information to store
  93. :type data: dict
  94. :return: the document, after the update
  95. :rtype: dict
  96. """
  97. db = self.connect()
  98. data = data or {}
  99. if '_id' in data:
  100. del data['_id']
  101. db[collection].update({'_id': ObjectId(_id)}, {'$set': data})
  102. return self.get(collection, _id)
  103. def merge(self, collection, data, searchBy):
  104. """Update an existing document.
  105. :param collection: update a document in this collection
  106. :type collection: str
  107. :param data: the document to store or merge with an existing one
  108. :type data: dict
  109. :return: a tuple with a boolean (True if an existing document was updated, and the _id of the document)
  110. :rtype: tuple
  111. """
  112. db = self.connect()
  113. _or = []
  114. for searchPattern in searchBy:
  115. try:
  116. _or.append(dict([(k, data[k]) for k in searchPattern]))
  117. except KeyError:
  118. continue
  119. if not _or:
  120. return False, None
  121. ret = db[collection].update({'$or': _or}, {'$set': data}, upsert=True)
  122. _id = ret.get('upserted')
  123. if _id is None:
  124. newDoc = db[collection].find_one(data)
  125. if newDoc:
  126. _id = newDoc['_id']
  127. return ret['updatedExisting'], _id
  128. def delete(self, collection, _id_or_query=None, force=False):
  129. """Remove one or more documents from a collection.
  130. :param collection: search the documents in this collection
  131. :type collection: str
  132. :param _id_or_query: unique ID of the document or query to match multiple documents
  133. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or dict
  134. :param force: force the deletion of all documents, when `_id_or_query` is empty
  135. :type force: bool
  136. """
  137. if not _id_or_query and not force:
  138. return
  139. db = self.connect()
  140. if not isinstance(_id_or_query, (ObjectId, dict)):
  141. _id_or_query = ObjectId(_id_or_query)
  142. db[collection].remove(_id_or_query)