mongo.py 2.5 KB

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