backend.py 8.7 KB

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