mongo.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 bson.objectid import ObjectId
  8. from bson.binary import Binary
  9. import json
  10. from datetime import datetime
  11. import gridfs
  12. # from transport import Reader,Writer
  13. import sys
  14. if sys.version_info[0] > 2 :
  15. from transport.common import Reader, Writer
  16. else:
  17. from common import Reader, Writer
  18. import json
  19. import re
  20. class Mongo :
  21. """
  22. Basic mongodb functions are captured here
  23. """
  24. def __init__(self,**args):
  25. """
  26. :dbname database name/identifier
  27. :host host and port of the database by default localhost:27017
  28. :username username for authentication
  29. :password password for current user
  30. """
  31. host = args['host'] if 'host' in args else 'localhost:27017'
  32. if 'user' in args and 'password' in args:
  33. self.client = MongoClient(host,
  34. username=args['username'] ,
  35. password=args['password'] ,
  36. authMechanism='SCRAM-SHA-256')
  37. else:
  38. self.client = MongoClient(host,maxPoolSize=10000)
  39. self.uid = args['doc'] #-- document identifier
  40. self.dbname = args['dbname'] if 'dbname' in args else args['db']
  41. self.db = self.client[self.dbname]
  42. def isready(self):
  43. p = self.dbname in self.client.list_database_names()
  44. q = self.uid in self.client[self.dbname].list_collection_names()
  45. return p and q
  46. def close(self):
  47. self.client.close()
  48. class MongoReader(Mongo,Reader):
  49. """
  50. This class will read from a mongodb data store and return the content of a document (not a collection)
  51. """
  52. def __init__(self,**args):
  53. Mongo.__init__(self,**args)
  54. def read(self,**args):
  55. if 'mongo' in args :
  56. #
  57. # @TODO:
  58. cmd = args['mongo']
  59. r = []
  60. out = self.db.command(cmd)
  61. #@TODO: consider using a yield (generator) works wonders
  62. while True :
  63. if 'values' in out :
  64. r += out['values']
  65. if 'cursor' in out :
  66. key = 'firstBatch' if 'firstBatch' in out['cursor'] else 'nextBatch'
  67. else:
  68. key = 'n'
  69. if 'cursor' in out and out['cursor'][key] :
  70. r += list(out['cursor'][key])
  71. elif key in out and out[key]:
  72. r.append (out[key])
  73. # yield out['cursor'][key]
  74. if key not in ['firstBatch','nextBatch'] or ('cursor' in out and out['cursor']['id'] == 0) :
  75. break
  76. else:
  77. out = self.db.command({"getMore":out['cursor']['id'],"collection":out['cursor']['ns'].split(".")[-1]})
  78. return r
  79. else:
  80. collection = self.db[self.uid]
  81. _filter = args['filter'] if 'filter' in args else {}
  82. return collection.find(_filter)
  83. def view(self,**args):
  84. """
  85. This function is designed to execute a view (map/reduce) operation
  86. """
  87. pass
  88. class MongoWriter(Mongo,Writer):
  89. """
  90. This class is designed to write to a mongodb collection within a database
  91. """
  92. def __init__(self,**args):
  93. Mongo.__init__(self,**args)
  94. def upload(self,**args) :
  95. """
  96. This function will upload a file to the current database (using GridFS)
  97. :param data binary stream/text to be stored
  98. :param filename filename to be used
  99. :param encoding content_encoding (default utf-8)
  100. """
  101. if 'encoding' not in args :
  102. args['encoding'] = 'utf-8'
  103. gfs = GridFS(self.db)
  104. gfs.put(**args)
  105. def archive(self):
  106. """
  107. This function will archive documents to the
  108. """
  109. collection = self.db[self.uid]
  110. rows = list(collection.find())
  111. for row in rows :
  112. if type(row['_id']) == ObjectId :
  113. row['_id'] = str(row['_id'])
  114. stream = Binary(json.dumps(collection).encode())
  115. collection.delete_many({})
  116. now = "-".join([str(datetime.now().year()),str(datetime.now().month), str(datetime.now().day)])
  117. name = ".".join([self.uid,'archive',now])+".json"
  118. description = " ".join([self.uid,'archive',str(len(rows))])
  119. self.upload(filename=name,data=stream,description=description,content_type='application/json')
  120. # gfs = GridFS(self.db)
  121. # gfs.put(filename=name,description=description,data=stream,encoding='utf-8')
  122. # self.write({{"filename":name,"file":stream,"description":descriptions}})
  123. pass
  124. def write(self,info):
  125. """
  126. This function will write to a given collection i.e add a record to a collection (no updates)
  127. @param info new record in the collection to be added
  128. """
  129. # document = self.db[self.uid].find()
  130. collection = self.db[self.uid]
  131. # if type(info) == list :
  132. # self.db[self.uid].insert_many(info)
  133. # else:
  134. if type(info) == list or type(info) == pd.DataFrame :
  135. self.db[self.uid].insert_many(info if type(info) == list else info.to_dict(orient='records'))
  136. else:
  137. self.db[self.uid].insert_one(info)
  138. def set(self,document):
  139. """
  140. if no identifier is provided the function will delete the entire collection and set the new document.
  141. Please use this function with great care (archive the content first before using it... for safety)
  142. """
  143. collection = self.db[self.uid]
  144. if collection.count_document() > 0 and '_id' in document:
  145. id = document['_id']
  146. del document['_id']
  147. collection.find_one_and_replace({'_id':id},document)
  148. else:
  149. collection.delete_many({})
  150. self.write(info)
  151. def close(self):
  152. Mongo.close(self)
  153. # collecton.update_one({"_id":self.uid},document,True)