backend.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 re
  15. import pymongo
  16. from bson.objectid import ObjectId
  17. re_objectid = re.compile(r'[0-9a-f]{24}')
  18. class EventManDB(object):
  19. """MongoDB connector."""
  20. db = None
  21. connection = None
  22. def __init__(self, url=None, dbName='eventman'):
  23. """Initialize the instance, connecting to the database.
  24. :param url: URL of the database
  25. :type url: str (or None to connect to localhost)
  26. """
  27. self._url = url
  28. self._dbName = dbName
  29. self.connect(url)
  30. def connect(self, url=None, dbName=None):
  31. """Connect to the database.
  32. :param url: URL of the database
  33. :type url: str (or None to connect to localhost)
  34. :return: the database we're connected to
  35. :rtype: :class:`~pymongo.database.Database`
  36. """
  37. if self.db is not None:
  38. return self.db
  39. if url:
  40. self._url = url
  41. if dbName:
  42. self._dbName = dbName
  43. self.connection = pymongo.MongoClient(self._url)
  44. self.db = self.connection[self._dbName]
  45. return self.db
  46. def convert_obj(self, obj):
  47. """Convert a string to an object for MongoDB.
  48. :param obj: object to convert
  49. """
  50. try:
  51. return ObjectId(obj)
  52. except:
  53. pass
  54. try:
  55. return int(obj)
  56. except:
  57. pass
  58. return obj
  59. def convert(self, seq):
  60. if isinstance(seq, dict):
  61. d = {}
  62. for key, item in seq.iteritems():
  63. d[key] = self.convert_obj(item)
  64. return d
  65. if isinstance(seq, (list, tuple)):
  66. return [self.convert_obj(x) for x in seq]
  67. return self.convert_obj(seq)
  68. def get(self, collection, _id):
  69. """Get a single document with the specified `_id`.
  70. :param collection: search the document in this collection
  71. :type collection: str
  72. :param _id: unique ID of the document
  73. :type _id: str or :class:`~bson.objectid.ObjectId`
  74. :return: the document with the given `_id`
  75. :rtype: dict
  76. """
  77. results = self.query(collection, self.convert({'_id': _id}))
  78. return results and results[0] or {}
  79. def query(self, collection, query=None):
  80. """Get multiple documents matching a query.
  81. :param collection: search for documents in this collection
  82. :type collection: str
  83. :param query: search for documents with those attributes
  84. :type query: dict or None
  85. :return: list of matching documents
  86. :rtype: list
  87. """
  88. db = self.connect()
  89. query = self.convert(query or {})
  90. return list(db[collection].find(query))
  91. def add(self, collection, data):
  92. """Insert a new document.
  93. :param collection: insert the document in this collection
  94. :type collection: str
  95. :param data: the document to store
  96. :type data: dict
  97. :return: the document, as created in the database
  98. :rtype: dict
  99. """
  100. db = self.connect()
  101. _id = db[collection].insert(data)
  102. return self.get(collection, _id)
  103. def insertOne(self, collection, data):
  104. """Insert a document, avoiding duplicates.
  105. :param collection: update a document in this collection
  106. :type collection: str
  107. :param data: the document information to store
  108. :type data: dict
  109. :return: True if the document was already present
  110. :rtype: bool
  111. """
  112. db = self.connect()
  113. ret = db[collection].update(data, {'$set': data}, upsert=True)
  114. return ret['updatedExisting']
  115. def update(self, collection, _id_or_query, data, operator='$set', create=True):
  116. """Update an existing document.
  117. :param collection: update a document in this collection
  118. :type collection: str
  119. :param _id: unique ID of the document to be updated
  120. :type _id: str or :class:`~bson.objectid.ObjectId`
  121. :param data: the updated information to store
  122. :type data: dict
  123. :return: the document, after the update
  124. :rtype: dict
  125. """
  126. db = self.connect()
  127. data = data or {}
  128. if _id_or_query is None:
  129. _id_or_query = {'_id': None}
  130. elif isinstance(_id_or_query, (list, tuple)):
  131. _id_or_query = {'$or': self.buildSearchPattern(data, _id_or_query)}
  132. elif not isinstance(_id_or_query, dict):
  133. _id_or_query = {'_id': _id_or_query}
  134. _id_or_query = self.convert(_id_or_query)
  135. if '_id' in data:
  136. del data['_id']
  137. res = db[collection].find_and_modify(query=_id_or_query,
  138. update={operator: data}, full_response=True, new=True, upsert=create)
  139. lastErrorObject = res.get('lastErrorObject') or {}
  140. return lastErrorObject.get('updatedExisting', False), res.get('value') or {}
  141. def buildSearchPattern(self, data, searchBy):
  142. _or = []
  143. for searchPattern in searchBy:
  144. try:
  145. _or.append(dict([(k, data[k]) for k in searchPattern]))
  146. except KeyError:
  147. continue
  148. return _or
  149. def merge(self, collection, data, searchBy, operator='$set'):
  150. """Update an existing document.
  151. :param collection: update a document in this collection
  152. :type collection: str
  153. :param data: the document to store or merge with an existing one
  154. :type data: dict
  155. :return: a tuple with a boolean (True if an existing document was updated, and the _id of the document)
  156. :rtype: tuple
  157. """
  158. db = self.connect()
  159. _or = []
  160. for searchPattern in searchBy:
  161. try:
  162. _or.append(dict([(k, data[k]) for k in searchPattern]))
  163. except KeyError:
  164. continue
  165. if not _or:
  166. return False, None
  167. # Two-steps merge/find to count the number of merged documents
  168. ret = db[collection].update({'$or': _or}, {operator: data}, upsert=True)
  169. _id = ret.get('upserted')
  170. if _id is None:
  171. newDoc = db[collection].find_one(data)
  172. if newDoc:
  173. _id = newDoc['_id']
  174. return ret['updatedExisting'], _id
  175. def delete(self, collection, _id_or_query=None, force=False):
  176. """Remove one or more documents from a collection.
  177. :param collection: search the documents in this collection
  178. :type collection: str
  179. :param _id_or_query: unique ID of the document or query to match multiple documents
  180. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or dict
  181. :param force: force the deletion of all documents, when `_id_or_query` is empty
  182. :type force: bool
  183. """
  184. if not _id_or_query and not force:
  185. return
  186. db = self.connect()
  187. if not isinstance(_id_or_query, dict):
  188. _id_or_query = {'_id': _id_or_query}
  189. db[collection].remove(_id_or_query)