backend.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. # map operations on lists of items.
  23. _operations = {
  24. 'update': '$set',
  25. 'append': '$push',
  26. 'appendUnique': '$addToSet',
  27. 'delete': '$pull'
  28. }
  29. def __init__(self, url=None, dbName='eventman'):
  30. """Initialize the instance, connecting to the database.
  31. :param url: URL of the database
  32. :type url: str (or None to connect to localhost)
  33. """
  34. self._url = url
  35. self._dbName = dbName
  36. self.connect(url)
  37. def connect(self, url=None, dbName=None):
  38. """Connect to the database.
  39. :param url: URL of the database
  40. :type url: str (or None to connect to localhost)
  41. :return: the database we're connected to
  42. :rtype: :class:`~pymongo.database.Database`
  43. """
  44. if self.db is not None:
  45. return self.db
  46. if url:
  47. self._url = url
  48. if dbName:
  49. self._dbName = dbName
  50. self.connection = pymongo.MongoClient(self._url)
  51. self.db = self.connection[self._dbName]
  52. return self.db
  53. def convert_obj(self, obj):
  54. """Convert an object in a format suitable to be stored in MongoDB.
  55. :param obj: object to convert
  56. :return: object that can be stored in MongoDB.
  57. """
  58. if obj is None:
  59. return None
  60. if isinstance(obj, bool):
  61. return obj
  62. try:
  63. return ObjectId(obj)
  64. except:
  65. pass
  66. try:
  67. i_obj = int(obj)
  68. if i_obj > 2**64 - 1:
  69. return obj
  70. return i_obj
  71. except:
  72. pass
  73. return obj
  74. def convert(self, seq):
  75. """Convert an object in a format suitable to be stored in MongoDB,
  76. descending lists, tuples and dictionaries (a copy is returned).
  77. :param seq: sequence or object to convert
  78. :return: object that can be stored in MongoDB.
  79. """
  80. if isinstance(seq, dict):
  81. d = {}
  82. for key, item in seq.iteritems():
  83. d[key] = self.convert(item)
  84. return d
  85. if isinstance(seq, (list, tuple)):
  86. return [self.convert(x) for x in seq]
  87. return self.convert_obj(seq)
  88. def get(self, collection, _id):
  89. """Get a single document with the specified `_id`.
  90. :param collection: search the document in this collection
  91. :type collection: str
  92. :param _id: unique ID of the document
  93. :type _id: str or :class:`~bson.objectid.ObjectId`
  94. :return: the document with the given `_id`
  95. :rtype: dict
  96. """
  97. results = self.query(collection, self.convert({'_id': _id}))
  98. return results and results[0] or {}
  99. def query(self, collection, query=None):
  100. """Get multiple documents matching a query.
  101. :param collection: search for documents in this collection
  102. :type collection: str
  103. :param query: search for documents with those attributes
  104. :type query: dict or None
  105. :return: list of matching documents
  106. :rtype: list
  107. """
  108. db = self.connect()
  109. query = self.convert(query or {})
  110. return list(db[collection].find(query))
  111. def add(self, collection, data):
  112. """Insert a new document.
  113. :param collection: insert the document in this collection
  114. :type collection: str
  115. :param data: the document to store
  116. :type data: dict
  117. :return: the document, as created in the database
  118. :rtype: dict
  119. """
  120. db = self.connect()
  121. data = self.convert(data)
  122. _id = db[collection].insert(data)
  123. return self.get(collection, _id)
  124. def insertOne(self, collection, data):
  125. """Insert a document, avoiding duplicates.
  126. :param collection: update a document in this collection
  127. :type collection: str
  128. :param data: the document information to store
  129. :type data: dict
  130. :return: True if the document was already present
  131. :rtype: bool
  132. """
  133. db = self.connect()
  134. data = self.convert(data)
  135. ret = db[collection].update(data, {'$set': data}, upsert=True)
  136. return ret['updatedExisting']
  137. def _buildSearchPattern(self, data, searchBy):
  138. """Return an OR condition."""
  139. _or = []
  140. for searchPattern in searchBy:
  141. try:
  142. _or.append(dict([(k, data[k]) for k in searchPattern if k in data]))
  143. except KeyError:
  144. continue
  145. return _or
  146. def update(self, collection, _id_or_query, data, operation='update',
  147. updateList=None, create=True):
  148. """Update an existing document or create it, if requested.
  149. _id_or_query can be an ID, a dict representing a query or a list of tuples.
  150. In the latter case, the tuples are put in OR; a tuple match if all of its
  151. items from 'data' are contained in the document.
  152. :param collection: update a document in this collection
  153. :type collection: str
  154. :param _id_or_query: ID of the document to be updated, or a query or a list of attributes in the data that must match
  155. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or iterable
  156. :param data: the updated information to store
  157. :type data: dict
  158. :param operation: operation used to update the document or a portion of it, like a list (update, append, appendUnique, delete)
  159. :type operation: str
  160. :param updateList: if set, it's considered the name of a list (the first matching element will be updated)
  161. :type updateList: str
  162. :param create: if True, the document is created if no document matches
  163. :type create: bool
  164. :return: a boolean (True if an existing document was updated) and the document after the update
  165. :rtype: tuple of (bool, dict)
  166. """
  167. db = self.connect()
  168. data = self.convert(data or {})
  169. _id_or_query = self.convert(_id_or_query)
  170. if isinstance(_id_or_query, (list, tuple)):
  171. _id_or_query = {'$or': self._buildSearchPattern(data, _id_or_query)}
  172. elif not isinstance(_id_or_query, dict):
  173. _id_or_query = {'_id': _id_or_query}
  174. if '_id' in data:
  175. del data['_id']
  176. operator = self._operations.get(operation)
  177. if updateList:
  178. newData = {}
  179. for key, value in data.iteritems():
  180. newData['%s.$.%s' % (updateList, key)] = value
  181. data = newData
  182. res = db[collection].find_and_modify(query=_id_or_query,
  183. update={operator: data}, full_response=True, new=True, upsert=create)
  184. lastErrorObject = res.get('lastErrorObject') or {}
  185. return lastErrorObject.get('updatedExisting', False), res.get('value') or {}
  186. def delete(self, collection, _id_or_query=None, force=False):
  187. """Remove one or more documents from a collection.
  188. :param collection: search the documents in this collection
  189. :type collection: str
  190. :param _id_or_query: unique ID of the document or query to match multiple documents
  191. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or dict
  192. :param force: force the deletion of all documents, when `_id_or_query` is empty
  193. :type force: bool
  194. """
  195. if not _id_or_query and not force:
  196. return
  197. db = self.connect()
  198. if not isinstance(_id_or_query, dict):
  199. _id_or_query = {'_id': _id_or_query}
  200. _id_or_query = self.convert(_id_or_query)
  201. db[collection].remove(_id_or_query)