No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

datasource.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. import pymongo
  3. from pymongo import MongoClient
  4. from pymongo.errors import BulkWriteError
  5. import urllib
  6. # TODO Positionner cette variable dans les settings
  7. DEFAULT_CONNECTION = {
  8. 'host': 'localhost',
  9. 'port': 27017,
  10. 'login': 'login', # TODO modifier la valeur
  11. 'password': 'password', # TODO modifier la valeur
  12. 'dbname': 'lodel'
  13. }
  14. class MongoDbDataSource(object):
  15. def __init__(self, module=pymongo, connection_args=DEFAULT_CONNECTION):
  16. connection_string = 'mongodb://%s:%s@%s:%s' % (connection_args['login'],
  17. urllib.quote_plus(connection_args['password']),
  18. connection_args['host'],
  19. connection_args['port'])
  20. self.connection = MongoClient(connection_string)
  21. self.database = self.connection[connection_args['dbname']]
  22. ## @brief Inserts a list of records in a given collection
  23. #
  24. # @param collection_name str : name of the MongoDB collection in which we will insert the records
  25. # @param datas list : list of dictionaries corresponding to the records
  26. # @throw BulkWriteError : is thrown when an error occurs during the execution of the ordered bulk operations
  27. def insert(self, collection_name, datas):
  28. collection = self.database[collection_name]
  29. bulk = collection.initialize_ordered_bulk_op()
  30. # TODO check if all the elements of the list are dictionaries
  31. bulk.insert_many(datas)
  32. try:
  33. result = bulk.execute()
  34. except BulkWriteError as bwe:
  35. pass # TODO Add the behavior in case of an exception => bwe.details['writeErrors'], is a list of error info dicts
  36. return result['nInserted']
  37. def select(self):
  38. pass
  39. def update(self):
  40. pass
  41. def delete(self, target_cls, uid):
  42. uidname = target_cls.uidname
  43. collection_name = target_cls.collection_name
  44. result = self.database[collection_name].delete_many({uidname: uid})
  45. return result.deteled_count