mongo.py 6.2 KB

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