__init__.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. """
  2. (c) 2019 Healthcare/IO 1.0
  3. Vanderbilt University Medical Center, Health Information Privacy Laboratory
  4. https://hiplab.mc.vanderbilt.edu/healthcareio
  5. Authors:
  6. Khanhly Nguyen,
  7. Steve L. Nyemba<steve.l.nyemba@vanderbilt.edu>
  8. License:
  9. MIT, terms are available at https://opensource.org/licenses/MIT
  10. This parser was originally written by Khanhly Nguyen for her internship and is intended to parse x12 835,837 and others provided the appropriate configuration
  11. USAGE :
  12. - COMMAND LINE
  13. - EMBEDDED
  14. """
  15. import hashlib
  16. import json
  17. import os
  18. import sys
  19. from itertools import islice
  20. from multiprocessing import Process
  21. import transport
  22. import jsonmerge
  23. import copy
  24. class void :
  25. pass
  26. class Formatters :
  27. def __init__(self):
  28. # self.config = config
  29. self.get = void()
  30. self.get.config = self.get_config
  31. self.parse = void()
  32. self.parse.sv3 = self.sv3
  33. self.parse.sv2 = self.sv2
  34. self.sv2_parser = self.sv2
  35. self.sv3_parser = self.sv3
  36. self.sv3_parse = self.sv3
  37. self.format_proc = self.procedure
  38. self.format_diag = self.diagnosis
  39. self.parse.procedure = self.procedure
  40. self.parse.diagnosis = self.diagnosis
  41. self.parse.date = self.date
  42. self.format_date = self.date
  43. self.format_pos = self.pos
  44. self.format_time = self.time
  45. def split(self,row,sep='*',prefix='HI') :
  46. """
  47. This function is designed to split an x12 row and
  48. """
  49. value = []
  50. if row.startswith(prefix) is False:
  51. for row_value in row.replace('~','').split(sep) :
  52. if '>' in row_value and not row_value.startswith('HC'):
  53. # if row_value.startswith('HC') or row_value.startswith('AD'):
  54. if row_value.startswith('AD'):
  55. value += row_value.split('>')[:2]
  56. pass
  57. else:
  58. value += [row_value]
  59. # value += row_value.split('>') if row.startswith('CLM') is False else [row_value]
  60. else :
  61. value.append(row_value.replace('\n',''))
  62. value = [xchar.replace('\r','') for xchar in value] #row.replace('~','').split(sep)
  63. else:
  64. value = [ [prefix]+ self.split(item,'>') for item in row.replace('~','').split(sep)[1:] ]
  65. return value if type(value) == list and type(value[0]) != list else value[0]
  66. def get_config(self,config,row):
  67. """
  68. This function will return the meaningfull parts of the configuration for a given item
  69. """
  70. _row = list(row) if type(row[0]) == str else list(row[0])
  71. _info = config[_row[0]] if _row[0] in config else {}
  72. _rinfo = {}
  73. key = None
  74. if '@ref' in _info:
  75. keys = list(set(_row) & set(_info['@ref'].keys()))
  76. if keys :
  77. _rinfo = {}
  78. for key in keys :
  79. _rinfo = jsonmerge.merge(_rinfo,_info['@ref'][key])
  80. return _rinfo
  81. # key = key[0]
  82. # return _info['@ref'][key]
  83. else:
  84. return {}
  85. if not _info and 'SIMILAR' in config:
  86. #
  87. # Let's look for the nearest key using the edit distance
  88. if _row[0] in config['SIMILAR'] :
  89. key = config['SIMILAR'][_row[0]]
  90. _info = config[key]
  91. return _info
  92. def hash(self,value):
  93. salt = os.environ['HEALTHCAREIO_SALT'] if 'HEALTHCAREIO_SALT' in os.environ else ''
  94. _value = str(value)+ salt
  95. if sys.version_info[0] > 2 :
  96. return hashlib.md5(_value.encode('utf-8')).hexdigest()
  97. else:
  98. return hashlib.md5(_value).hexdigest()
  99. def suppress (self,value):
  100. return 'N/A'
  101. def date(self,value):
  102. value = value if type(value) != list else "-".join(value)
  103. if len(value) > 8 or '-' in value:
  104. #
  105. # This is the case of a thru date i.e the first part should be provided in a 435 entry
  106. #
  107. fdate = "-".join([value[:8][:4],value[:8][4:6],value[:8][6:8]])
  108. tdate = "-".join([value[9:][:4],value[9:][4:6],value[9:][6:8]])
  109. return {"from":fdate,"to":tdate}
  110. if len(value) == 8 :
  111. year = value[:4]
  112. month = value[4:6]
  113. day = value[6:]
  114. return "-".join([year,month,day])[:10] #{"year":year,"month":month,"day":day}
  115. elif len(value) == 6 :
  116. year = '20' + value[:2]
  117. month = value[2:4]
  118. day = value[4:]
  119. elif value.isnumeric() and len(value) >= 10:
  120. #
  121. # Here I a will assume we have a numeric vale
  122. year = value[:4]
  123. month= value[4:6]
  124. day = value[6:8]
  125. else:
  126. #
  127. # We have a date formatting issue
  128. return value
  129. return "-".join([year,month,day])
  130. def time(self,value):
  131. pass
  132. def sv3(self,value):
  133. if '>' in value [1]:
  134. terms = value[1].split('>')
  135. return {'type':terms[0],'code':terms[1],"amount":float(value[2])}
  136. else:
  137. return {"code":value[2],"type":value[1],"amount":float(value[3])}
  138. def sv2(self,value):
  139. #
  140. # @TODO: Sometimes there's a suffix (need to inventory all the variations)
  141. #
  142. if '>' in value or ':' in value:
  143. xchar = '>' if '>' in value else ':'
  144. _values = value.split(xchar)
  145. modifier = {}
  146. if len(_values) > 2 :
  147. modifier= {"code":_values[2]}
  148. if len(_values) > 3 :
  149. modifier['type'] = _values[3]
  150. _value = {"code":_values[1],"type":_values[0]}
  151. if modifier :
  152. _value['modifier'] = modifier
  153. return _value
  154. else:
  155. return value
  156. def procedure(self,value):
  157. for xchar in [':','<','|','>'] :
  158. if xchar in value and len(value.split(xchar)) > 1 :
  159. #_value = {"type":value.split(':')[0].strip(),"code":value.split(':')[1].strip()}
  160. _value = {"type":value.split(xchar)[0].strip(),"code":value.split(xchar)[1].strip()}
  161. if len(value.split(xchar)) >2 :
  162. index = 1;
  163. for modifier in value.split(xchar)[2:] :
  164. _value['modifier_'+str(index)] = modifier
  165. index += 1
  166. break
  167. else:
  168. _value = str(value)
  169. return _value
  170. def diagnosis(self,value):
  171. return [ {"code":item[2], "type":item[1]} for item in value if len(item) > 1]
  172. def parse_loc(self,value):
  173. if ':' in value :
  174. return dict(zip(['place_of_service','claim_indicator','claim_frequency'],value.split(':')))
  175. def pos(self,value):
  176. """
  177. formatting place of service information within a segment (REF)
  178. @TODO: In order to accomodate the other elements they need to be specified in the configuration
  179. Otherwise it causes problems on export
  180. """
  181. xchar = '>' if '>' in value else ':'
  182. x = value.split(xchar)
  183. x = {"place_of_service":x[0],"indicator":x[1],"frequency":x[2]} if len(x) == 3 else {"place_of_service":x[0],"indicator":None,"frequency":None}
  184. return x
  185. class Parser (Process):
  186. @staticmethod
  187. def setup (path):
  188. # self.config = _config['parser']
  189. config = json.loads(open(path).read())
  190. _config = config['parser']
  191. #
  192. # The parser may need some editing provided, this allows ease of developement and using alternate configurations
  193. #
  194. if type(_config['837']) == str or type(_config['835']) == str :
  195. for _id in ['837','835'] :
  196. if type(_config[_id]) == str and os.path.exists(_config[_id]):
  197. _config[_id] = json.loads(open(_config[_id]).read())
  198. if type(_config[_id]) == dict :
  199. _config[_id] = [_config[_id]]
  200. config['parser'] = _config
  201. return config
  202. def __init__(self,path):
  203. """
  204. :path path of the configuration file (it can be absolute)
  205. """
  206. Process.__init__(self)
  207. self.utils = Formatters()
  208. self.get = void()
  209. self.get.value = self.get_map
  210. self.get.default_value = self.get_default_value
  211. # _config = json.loads(open(path).read())
  212. self._custom_config = self.get_custom(path)
  213. # self.config = _config['parser']
  214. # #
  215. # # The parser may need some editing provided, this allows ease of developement and using alternate configurations
  216. # #
  217. # if type(self.config['837']) == str or type(self.config['835']) == str :
  218. # for _id in ['837','835'] :
  219. # if type(self.config[_id]) == str:
  220. # self.config[_id] = json.loads(open(self.config[_id]).read())
  221. # if type(self.config[_id]) == dict :
  222. # self.config[_id] = [self.config[_id]]
  223. _config = Parser.setup(path)
  224. self.config = _config['parser']
  225. self.store = _config['store']
  226. self.cache = {}
  227. self.files = []
  228. self.set = void()
  229. self.set.files = self.set_files
  230. self.emit = void()
  231. self.emit.pre = None
  232. self.emit.post = None
  233. def get_custom(self,path) :
  234. """
  235. :path path of the configuration file (it can be absolute)
  236. """
  237. #
  238. #
  239. _path = path.replace('config.json','')
  240. if _path.endswith(os.sep) :
  241. _path = _path[:-1]
  242. _config = {}
  243. _path = os.sep.join([_path,'custom'])
  244. if os.path.exists(_path) :
  245. files = os.listdir(_path)
  246. if files :
  247. fullname = os.sep.join([_path,files[0]])
  248. _config = json.loads ( (open(fullname)).read() )
  249. return _config
  250. def set_files(self,files):
  251. self.files = files
  252. def get_map(self,row,config,version=None):
  253. # label = config['label'] if 'label' in config else None
  254. handler = Formatters()
  255. if 'map' not in config and hasattr(handler,config['apply']):
  256. pointer = getattr(handler,config['apply'])
  257. object_value = pointer(row)
  258. return object_value
  259. #
  260. # Pull the goto configuration that skips rows
  261. #
  262. omap = config['map'] if not version or version not in config else config[version]
  263. anchors = config['anchors'] if 'anchors' in config else []
  264. rewrite = config['rewrite'] if 'rewrite' in config else {}
  265. if len(row) == 2 and row[0] == 'HI' :
  266. row = ([row[0]] + row[1].split(':'))
  267. if type(row[0]) == str:
  268. object_value = {}
  269. for key in omap :
  270. index = omap[key]
  271. if anchors and set(anchors) & set(row):
  272. _key = list(set(anchors) & set(row))[0]
  273. aindex = row.index(_key)
  274. index = aindex + index
  275. if index < len(row) :
  276. value = row[index]
  277. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  278. if config['cast'][key] in ['float','int']:
  279. try:
  280. value = eval(config['cast'][key])(value)
  281. except Exception as e:
  282. pass
  283. #
  284. # Sometimes shit hits the fan when the anchor is missing
  285. # This is typical but using the hardened function helps circumvent this (SV2,SV3)
  286. #
  287. elif hasattr(handler,config['cast'][key]):
  288. pointer = getattr(handler,config['cast'][key])
  289. value = pointer(value)
  290. else:
  291. print ("Missing Pointer ",key,config['cast'])
  292. if type(value) == dict :
  293. for objkey in value :
  294. if type(value[objkey]) == dict :
  295. continue
  296. if 'syn' in config and value[objkey] in config['syn'] :
  297. # value[objkey] = config['syn'][ value[objkey]]
  298. pass
  299. if key in rewrite :
  300. _key = rewrite[key]
  301. if _key in value :
  302. value = value[_key]
  303. else:
  304. value = ""
  305. value = {key:value} if key not in value else value
  306. else:
  307. if 'syn' in config and value in config['syn'] :
  308. # value = config['syn'][value]
  309. pass
  310. if type(value) == dict :
  311. object_value = jsonmerge.merge(object_value, value)
  312. else:
  313. object_value[key] = value
  314. else:
  315. #
  316. # we are dealing with a complex object
  317. object_value = []
  318. for row_item in row :
  319. value = self.get.value(row_item,config,version)
  320. object_value.append(value)
  321. return object_value
  322. def set_cache(self,tmp,_info) :
  323. """
  324. insert into cache a value that the, these are in reference to a loop
  325. """
  326. if 'cache' in _info :
  327. key = _info['cache']['key']
  328. value=_info['cache']['value']
  329. field = _info['cache']['field']
  330. if value in tmp :
  331. self.cache [key] = {field:tmp[value]}
  332. pass
  333. def get_cache(self,row) :
  334. """
  335. retrieve cache element for a current
  336. """
  337. key = row[0]
  338. return self.cache[key] if key in self.cache else {}
  339. def apply(self,content,_code) :
  340. """
  341. :content content of a file i.e a segment with the envelope
  342. :_code 837 or 835 (helps get the appropriate configuration)
  343. """
  344. util = Formatters()
  345. # header = default_value.copy()
  346. value = {}
  347. for row in content[:] :
  348. row = util.split(row.replace('\n','').replace('~',''))
  349. _info = util.get.config(self.config[_code][0],row)
  350. if self._custom_config and _code in self._custom_config:
  351. _cinfo = util.get.config(self._custom_config[_code],row)
  352. else:
  353. _cinfo = {}
  354. if _info or _cinfo:
  355. try:
  356. _info = jsonmerge.merge(_info,_cinfo)
  357. tmp = self.get.value(row,_info)
  358. if not tmp :
  359. continue
  360. #
  361. # At this point we have the configuration and the row parsed into values
  362. # We should check to see if we don't have anything in the cache to be added to it
  363. #
  364. if row[0] in self.cache :
  365. tmp = jsonmerge.merge(tmp,self.get_cache(row))
  366. if 'label' in _info :
  367. label = _info['label']
  368. if type(tmp) == list :
  369. value[label] = tmp if label not in value else value[label] + tmp
  370. else:
  371. # if 'DTM' in row :
  372. # print ([label,tmp,label in value])
  373. if label not in value :
  374. value[label] = []
  375. value[label].append(tmp)
  376. # if label not in value:
  377. # value[label] = [tmp]
  378. # else:
  379. # value[label].append(tmp)
  380. if '_index' not in tmp :
  381. #
  382. # In case we asked it to be overriden, then this will not apply
  383. # X12 occasionally requires references to other elements in a loop (alas)
  384. #
  385. tmp['_index'] = len(value[label]) -1
  386. elif 'field' in _info :
  387. name = _info['field']
  388. # value[name] = tmp
  389. # value = jsonmerge.merge(value,{name:tmp})
  390. if name not in value :
  391. value = dict(value,**{name:tmp})
  392. else:
  393. value[name] = dict(value[name],**tmp)
  394. else:
  395. value = dict(value,**tmp)
  396. pass
  397. except Exception as e :
  398. print (e.args[0])
  399. # print ('__',(dir(e.args)))
  400. pass
  401. #
  402. # At this point the object is completely built,
  403. # if there ar any attributes to be cached it will be done here
  404. #
  405. if 'cache' in _info :
  406. self.set_cache(tmp,_info)
  407. return value if value else {}
  408. def get_default_value(self,content,_code):
  409. util = Formatters()
  410. TOP_ROW = content[1].split('*')
  411. SUBMITTED_DATE = util.parse.date(TOP_ROW[4])
  412. CATEGORY= content[2].split('*')[1].strip()
  413. VERSION = content[1].split('*')[-1].replace('~','').replace('\n','')
  414. SENDER_ID = TOP_ROW[2]
  415. row = util.split(content[3])
  416. _info = util.get_config(self.config[_code][0],row)
  417. value = self.get.value(row,_info,VERSION) if _info else {}
  418. value['category'] = {"setid": _code,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  419. value["submitted"] = SUBMITTED_DATE
  420. value['sender_id'] = SENDER_ID
  421. # value = dict(value,**self.apply(content,_code))
  422. value = jsonmerge.merge(value,self.apply(content,_code))
  423. # Let's parse this for default values
  424. return value #jsonmerge.merge(value,self.apply(content,_code))
  425. def read(self,filename) :
  426. """
  427. :formerly get_content
  428. This function returns the of the EDI file parsed given the configuration specified. it is capable of identifying a file given the content
  429. :section loop prefix (HL, CLP)
  430. :config configuration with formatting rules, labels ...
  431. :filename location of the file
  432. """
  433. # section = section if section else config['SECTION']
  434. logs = []
  435. claims = []
  436. _code = 'UNKNOWN'
  437. try:
  438. self.cache = {}
  439. file = open(filename.strip())
  440. file = file.read().split('CLP')
  441. _code = '835'
  442. section = 'CLP'
  443. if len(file) == 1 :
  444. file = file[0].split('CLM') #.split('HL')
  445. _code = '837'
  446. section = 'CLM' #'HL'
  447. INITIAL_ROWS = file[0].split(section)[0].split('\n')
  448. if len(INITIAL_ROWS) == 1 :
  449. INITIAL_ROWS = INITIAL_ROWS[0].split('~')
  450. # for item in file[1:] :
  451. # item = item.replace('~','\n')
  452. # print (INITIAL_ROWS)
  453. DEFAULT_VALUE = self.get.default_value(INITIAL_ROWS,_code)
  454. DEFAULT_VALUE['name'] = filename.strip()
  455. file = section.join(file).split('\n')
  456. if len(file) == 1:
  457. file = file[0].split('~')
  458. #
  459. # In the initial rows, there's redundant information (so much for x12 standard)
  460. # index 1 identifies file type i.e CLM for claim and CLP for remittance
  461. segment = []
  462. index = 0;
  463. _toprows = []
  464. _default = None
  465. for row in file :
  466. row = row.replace('\r','')
  467. # if not segment and not row.startswith(section):
  468. # _toprows += [row]
  469. if row.startswith(section) and not segment:
  470. segment = [row]
  471. continue
  472. elif segment and not row.startswith(section):
  473. segment.append(row)
  474. if len(segment) > 1 and row.startswith(section):
  475. #
  476. # process the segment somewhere (create a thread maybe?)
  477. #
  478. _claim = self.apply(segment,_code)
  479. if _claim :
  480. _claim['index'] = index #len(claims)
  481. # claims.append(dict(DEFAULT_VALUE,**_claim))
  482. #
  483. # schema = [ {key:{"mergeStrategy":"append" if list( type(_claim[key])) else "overwrite"}} for key in _claim.keys()] # if type(_claim[key]) == list]
  484. # _schema = set(DEFAULT_VALUE.keys()) - schema
  485. # if schema :
  486. # schema = {"properties":dict.fromkeys(schema,{"mergeStrategy":"append"})}
  487. # else:
  488. # schema = {"properties":{}}
  489. # schema = jsonmerge.merge(schema['properties'],dict.fromkeys(_schema,{"mergeStrategy":"overwrite"}))
  490. schema = {"properties":{}}
  491. for attr in _claim.keys() :
  492. schema['properties'][attr] = {"mergeStrategy": "append" if type(_claim[attr]) == list else "overwrite" }
  493. merger = jsonmerge.Merger(schema)
  494. _baseclaim = None
  495. _baseclaim = merger.merge(_baseclaim,copy.deepcopy(DEFAULT_VALUE))
  496. _claim = merger.merge(_baseclaim,_claim)
  497. # _claim = merger.merge(DEFAULT_VALUE.copy(),_claim)
  498. claims.append( _claim)
  499. segment = [row]
  500. index += 1
  501. pass
  502. #
  503. # Handling the last claim found
  504. if segment and segment[0].startswith(section) :
  505. # default_claim = dict({"name":index},**DEFAULT_VALUE)
  506. claim = self.apply(segment,_code)
  507. if claim :
  508. claim['index'] = len(claims)
  509. # schema = [key for key in claim.keys() if type(claim[key]) == list]
  510. # if schema :
  511. # schema = {"properties":dict.fromkeys(schema,{"mergeStrategy":"append"})}
  512. # else:
  513. # print (claim.keys())
  514. # schema = {}
  515. #
  516. # @TODO: Fix merger related to schema (drops certain fields ... NOT cool)
  517. # merger = jsonmerge.Merger(schema)
  518. # top_row_claim = self.apply(_toprows,_code)
  519. # claim = merger.merge(claim,self.apply(_toprows,_code))
  520. # claims.append(dict(DEFAULT_VALUE,**claim))
  521. schema = {"properties":{}}
  522. for attr in claim.keys() :
  523. schema['properties'][attr] = {"mergeStrategy": "append" if type(claim[attr]) == list else "overwrite" }
  524. merger = jsonmerge.Merger(schema)
  525. _baseclaim = None
  526. _baseclaim = merger.merge(_baseclaim,copy.deepcopy(DEFAULT_VALUE))
  527. claim = merger.merge(_baseclaim,claim)
  528. claims.append(claim)
  529. # claims.append(merger.merge(DEFAULT_VALUE.copy(),claim))
  530. if type(file) != list :
  531. file.close()
  532. # x12_file = open(filename.strip(),errors='ignore').read().split('\n')
  533. except Exception as e:
  534. logs.append ({"parse":_code,"completed":False,"name":filename,"msg":e.args[0]})
  535. return [],logs,None
  536. rate = 0 if len(claims) == 0 else (1 + index)/len(claims)
  537. logs.append ({"parse":"claims" if _code == '837' else 'remits',"completed":True,"name":filename,"rate":rate})
  538. # self.finish(claims,logs,_code)
  539. return claims,logs,_code
  540. def run(self):
  541. if self.emit.pre :
  542. self.emit.pre()
  543. for filename in self.files :
  544. content,logs,_code = self.read(filename)
  545. self.finish(content,logs,_code)
  546. def finish(self,content,logs,_code) :
  547. args = self.store
  548. _args = json.loads(json.dumps(self.store))
  549. ISNEW_MONGO = 'provider' in args and args['provider'] in ['mongo', 'mongodb']
  550. ISLEG_MONGO = ('type' in args and args['type'] == 'mongo.MongoWriter')
  551. if ISLEG_MONGO or ISNEW_MONGO:
  552. if ISLEG_MONGO:
  553. # Legacy specification ...
  554. args['args']['doc'] = 'claims' if _code == '837' else 'remits'
  555. _args['args']['doc'] = 'logs'
  556. else:
  557. args['doc'] = 'claims' if _code == '837' else 'remits'
  558. _args['doc'] = 'logs'
  559. else:
  560. if 'type' in args :
  561. # Legacy specification ...
  562. args['args']['table'] = 'claims' if _code == '837' else 'remits'
  563. _args['args']['table'] = 'logs'
  564. table = args['args']['table']
  565. else:
  566. args['table']= 'claims' if _code == '837' else 'remits'
  567. _args['table'] = 'logs'
  568. table = args['table']
  569. writer = transport.factory.instance(**args)
  570. IS_SQLITE = type(writer) == transport.disk.SQLiteWriter
  571. if content:
  572. if IS_SQLITE :
  573. for row in content :
  574. writer.apply("""insert into :table(data) values (':values')""".replace(":values",json.dumps(row)).replace(":table",table) )
  575. else:
  576. writer.write(content)
  577. writer.close()
  578. if logs :
  579. logger = transport.factory.instance(**_args)
  580. if IS_SQLITE:
  581. for row in logs:
  582. logger.apply("""insert into logs values (':values')""".replace(":values",json.dumps(row)))
  583. else:
  584. logger.write(logs)
  585. logger.close()
  586. if self.emit.post :
  587. self.emit.post(content,logs)