mongo.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from pymongo import MongoClient
  2. # from transport import Reader,Writer
  3. from common import Reader, Writer
  4. import json
  5. class Mongo :
  6. """
  7. Basic mongodb functions are captured here
  8. """
  9. def __init__(self,**args):
  10. """
  11. :dbname database name/identifier
  12. :host host and port of the database
  13. :username username for authentication
  14. :password password for current user
  15. """
  16. host = args['host']
  17. if 'user' in args and 'password' in args:
  18. self.client = MongoClient(host,
  19. username=args['username'] ,
  20. password=args['password'] ,
  21. authMechanism='SCRAM-SHA-256')
  22. else:
  23. self.client = MongoClient()
  24. self.uid = args['doc'] #-- document identifier
  25. self.dbname = args['dbname']
  26. self.db = self.client[self.dbname]
  27. def isready(self):
  28. p = self.dbname in self.client.list_database_names()
  29. q = self.uid in self.client[self.dbname].list_collection_names()
  30. return p and q
  31. class MongoReader(Mongo,Reader):
  32. """
  33. This class will read from a mongodb data store and return the content of a document (not a collection)
  34. """
  35. def __init__(self,**args):
  36. Mongo.__init__(self,**args)
  37. def read(self,size=-1):
  38. collection = self.db[self.uid]
  39. return collection.find({})
  40. def view(self,**args):
  41. """
  42. This function is designed to execute a view (map/reduce) operation
  43. """
  44. pass
  45. class MongoWriter(Mongo,Writer):
  46. """
  47. This class is designed to write to a mongodb collection within a database
  48. """
  49. def __init__(self,**args):
  50. Mongo.__init__(self,**args)
  51. def write(self,**args):
  52. # document = self.db[self.uid].find()
  53. collection = self.db[self.uid]
  54. collection.update_one()
  55. self.db[self.uid].insert_one(args['row'])
  56. def set(self,document):
  57. collection = self.db[self.uid]
  58. if collection.count_document() > 0 :
  59. collection.delete({_id:self.uid})
  60. collecton.update_one({"_id":self.uid},document,True)