mongo.py 8.0 KB

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