customModel.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import json
  2. import operator
  3. import subprocess
  4. from dbController import DbController
  5. dbController = DbController();
  6. import requests
  7. import log
  8. import shutil
  9. from datetime import datetime
  10. logger = log.logger
  11. from userController import UserController
  12. userController =UserController();
  13. class CustomModel():
  14. def caculate_string(self,a, b, c):
  15. if a == None or c == None:
  16. return True
  17. d = {'<': operator.lt, '<=': operator.le, '=': operator.eq, '>': operator.gt, '>=': operator.ge}
  18. return d[b](str(a), str(c))
  19. def caculate_logic(self,a, b, c):
  20. d = {'<': operator.lt, '<=': operator.le, '=': operator.eq, '>': operator.gt, '>=': operator.ge}
  21. return d[b](float(a), float(c))
  22. def dataFilter(self, businessInfo, filter_str):
  23. field_json=json.loads(businessInfo['result'])
  24. filter_json=json.loads(filter_str);
  25. # with open('field.json', 'r', encoding='utf-8')as fp:
  26. filter_dict = {}
  27. for k in filter_json:
  28. # print(k)
  29. field_dict = {}
  30. if k in field_json.keys():
  31. for k2 in filter_json[k]:
  32. if k2 in field_json[k].keys():
  33. field_dict[k2] = field_json[k][k2]
  34. else:
  35. print('The field2 does not exist!')
  36. filter_dict[k] = field_dict
  37. else:
  38. print('The field does not exist!')
  39. with open('result.json', 'w', encoding='utf8')as fp:
  40. json.dump(filter_dict, fp, ensure_ascii=False)
  41. # print('filter finished!')
  42. return filter_dict
  43. def callCustom(self,field_json,model_path):
  44. # with open('field.json', 'r', encoding='utf-8')as fp:
  45. # field_json = json.load(fp)
  46. with open(model_path, 'r', encoding='utf-8')as fp:
  47. condition_json = json.load(fp)
  48. condition_result = []
  49. for k in condition_json.keys():
  50. select_data = condition_json[k]['select_data']
  51. condition_result_k2 = []
  52. logic_k2 = []
  53. for k2 in select_data:
  54. condition_result_k2.append(
  55. self.caculate_string(field_json[k2['first_class']][k2['second_class']], k2['logic'], k2['value']))
  56. logic_k2.append(k2['mark'])
  57. # print(condition_result_k2)
  58. temp_condition = condition_result_k2[0]
  59. for i in range(1, len(condition_result_k2)):
  60. if logic_k2[i] == 'AND':
  61. temp_condition = temp_condition and condition_result_k2[i]
  62. elif logic_k2[i] == 'OR':
  63. temp_condition = temp_condition or condition_result_k2[i]
  64. if condition_json[k]['result'] == '拒绝':
  65. temp_condition = not temp_condition
  66. condition_result.append(temp_condition)
  67. result = condition_result[0]
  68. # field_json = json.load(fp)
  69. #
  70. # with open('filter.json', 'r', encoding='utf-8')as fp:
  71. # filter_json = json.load(fp)
  72. filter_dict = {}
  73. # print(len(condition_result))
  74. for i in range(1, len(condition_result)):
  75. result = result and condition_result[i]
  76. # print("结果是"+str(result))
  77. return result
  78. def query_by_http(self, url, businessInfo):
  79. credit_json = businessInfo["result"]
  80. request_data = {
  81. 'queryReq': credit_json
  82. }
  83. # logger.info(json.dumps(request_data))
  84. headers = {"Content-Type": "application/json"}
  85. resp = requests.post(url, data=json.dumps(request_data), headers=headers)
  86. return resp.text
  87. def query_by_python(self, python_path, jsonFile):
  88. execute = "python {} '{}'".format(python_path, jsonFile)
  89. # print(execute)
  90. output = subprocess.Popen(execute, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  91. res = output.stdout.readlines()
  92. return res
  93. def query_by_java_jar(self,jar_path, jsonFile):
  94. execute = "java -jar {} '{}'".format(jar_path, jsonFile)
  95. # print(execute)
  96. output = subprocess.Popen(execute, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  97. res = output.stdout.readlines()
  98. return res
  99. def doCustomModel(self,productNum,businessInfo,xml_path,file_name,startTime):
  100. # 获取用户信息
  101. product_num = productNum
  102. file_name = file_name
  103. userController.getConn();
  104. user_list = userController.getUser();
  105. userController.getModelByUserAndNum(user_list,product_num);
  106. for user in user_list:
  107. if user["user_name"]=='test':
  108. model_list=user["model_list"];
  109. # if user.get('field_data') !=None:
  110. if model_list != []:
  111. for model in model_list:
  112. model_name = model["model_name"]
  113. else:
  114. dbController.getConn()
  115. parse_info = str(businessInfo["result"])
  116. parse_info = parse_info.replace("'", "\\'")
  117. filter_info = "没有设置自定义模型而无法解析"
  118. sql = "INSERT INTO filter_result(report_name,product_num,filter_info,parse_info,start_time) VALUES ('" + file_name + "', '" + productNum + "', '" + filter_info + "', '" + parse_info + "', '" + startTime + "')"
  119. # print(sql)
  120. dbController.execSql(sql)
  121. # if i==1:
  122. # break
  123. dbController.commit()
  124. userController.getFieldByUserAndModel(user_list,model_name);
  125. base_path="D:/jin_rong/model_data/"
  126. base_url="http://127.0.0.1:"
  127. # print(user_list)
  128. for user in user_list:
  129. model_list=user["model_list"];
  130. # if user.get('field_data') !=None:
  131. if 1:
  132. for model in model_list:
  133. # print(model)
  134. if(model.get('product_num')!=None):
  135. # print("11111");模型对应产品号非空才走下面流程
  136. print(model)
  137. if(model['product_num'].find(productNum)>=0 ):
  138. # ` 自定义模型
  139. print("模型类型是:"+str(model["model_type"]))
  140. if model["model_type"]==0:
  141. # read_data=json.loads(businessInfo['result'])
  142. # print(businessInfo["result"])
  143. # print("11111");#模型对应产品号非空才走下面流程
  144. if businessInfo["result"]=="":
  145. result = {"approveResult": "0", "rule": "白户"}
  146. uploadAudit(result, businessInfo["businessNum"], productNum)
  147. return 0
  148. # read_data = businessInfo
  149. parse_info = str(businessInfo["result"])
  150. parse_info = parse_info.replace("'","\\'")
  151. print("user['field_data']是")
  152. print(user)
  153. read_data = self.dataFilter(businessInfo, user['field_data']);
  154. #yuan在此更新数据库,插入字段组合的过滤结果read_data,500字段的解析结果businessInfo
  155. #字段组合过滤结果的表需更新,500字段解析结果表需新建
  156. endTime = str(datetime.now()) # 结束时间
  157. # dbController.getConn()
  158. # filter_info = str(read_data)
  159. # filter_info = filter_info.replace("'","\\'")
  160. # sql = "INSERT INTO filter_result(report_name,filter_info,parse_info) VALUES ('" + file_name + "', '"+ filter_info+"', '"+ parse_info +"')"
  161. # dbController.execSql(sql)
  162. # dbController.commit()
  163. inner_path = xml_path.replace("test_data", "test_data/execed_filter")
  164. # print(inner_path)
  165. txtPath = inner_path.replace(".xml", ".txt")
  166. # print("txt路径"+txtPath)
  167. with open(txtPath, 'w', encoding='utf-8') as fp:
  168. fp.write(str(read_data))
  169. # dbController.getConn()
  170. # report_name = file_name
  171. #
  172. # sql = "INSERT INTO parse_result(report_name,fmodel_name,result_info,created_by) " \
  173. # "VALUES ('" + report_name +"', '1', '"+ str(read_data)+"','1', 'test')"
  174. # print(sql)
  175. # dbController.execSql(sql)
  176. # dbController.commit()
  177. result=self.callCustom(read_data,base_path+user['user_name']+"_"+model['model_name']+'.json');
  178. if result:
  179. res = {"approveResult": "1"}
  180. # print("征信通过")
  181. # dbController.getConn()
  182. # # print(len(sqlMap))
  183. # sql = "INSERT INTO credit_approval(approval_result,credit_name) VALUES ('征信通过', '" + file_name + "')"
  184. # # print(sql)
  185. # dbController.execSql(sql)
  186. # # if i==1:
  187. # # break
  188. # dbController.commit()
  189. # yuan新增入库
  190. dbController.getConn()
  191. # filter_info = str(read_data)
  192. # filter_info = filter_info.replace("'", "\\'")
  193. filter_info = "征信通过"
  194. sql = "INSERT INTO filter_result(report_name,product_num,filter_info,parse_info,start_time,end_time) VALUES ('" + file_name + "', '" + productNum + "', '" + filter_info + "', '" + parse_info + "', '" + startTime + "', '" + endTime + "')"
  195. # print(sql)
  196. dbController.execSql(sql)
  197. dbController.commit()
  198. print("this is not a sadf")
  199. uploadAudit(res, businessInfo["businessNum"], productNum);
  200. #
  201. print("this is a sadf")
  202. return 0
  203. else:
  204. res = {"approveResult": "0"}
  205. # print("征信未通过")
  206. # yuan新增入库
  207. dbController.getConn()
  208. # filter_info = str(read_data)
  209. # filter_info = filter_info.replace("'", "\\'")
  210. filter_info = "征信失败"
  211. sql = "INSERT INTO filter_result(report_name,product_num,filter_info,parse_info,start_time,end_time) VALUES ('" + file_name + "', '" + productNum + "', '" + filter_info + "', '" + parse_info + "', '" + startTime + "', '" + endTime + "')"
  212. # print(sql)
  213. dbController.execSql(sql)
  214. dbController.commit()
  215. # 默认上传审批结果
  216. # print(res)
  217. # uploadAudit(res, businessInfo["businessNum"], productNum);
  218. #
  219. return 0
  220. elif model["model_type"]==1:
  221. read_data = self.dataFilter(businessInfo, user['field_data']);
  222. jsonPath = xml_path.replace(".xml", "_json.txt")
  223. with open(jsonPath, 'w', encoding='utf-8') as fp:
  224. json.dump(read_data, fp, ensure_ascii=False)
  225. result=self.query_by_java_jar(base_path+"/"+user['user_name']+"/"+model['other_data'],jsonPath);
  226. with open(jsonPath, 'w', encoding='utf-8') as fp:
  227. fp.write(json.dumps(result))
  228. uploadJsonFile(businessInfo, jsonPath)
  229. return 1
  230. elif model["model_type"] == 2:
  231. read_data = self.dataFilter(businessInfo, user['field_data']);
  232. jsonPath = xml_path.replace(".xml", "_json.txt")
  233. with open(jsonPath, 'w', encoding='utf-8') as fp:
  234. json.dump(read_data, fp, ensure_ascii=False)
  235. result=self.query_by_python(base_path+"/"+user['user_name']+"/"+model['other_data'],jsonPath);
  236. with open(jsonPath, 'w', encoding='utf-8') as fp:
  237. fp.write(json.dumps(result))
  238. uploadJsonFile(businessInfo, jsonPath)
  239. return 2
  240. elif model["model_type"] == 3:
  241. result=self.query_by_http(base_url+model['other_data'],businessInfo);
  242. jsonPath = xml_path.replace(".xml", "_json.txt")
  243. with open(jsonPath, 'w', encoding='utf-8') as fp:
  244. fp.write(json.dumps(result))
  245. uploadJsonFile(businessInfo, jsonPath)
  246. return 3
  247. elif model["model_type"]==4:
  248. uploadJsonFile(businessInfo,xml_path.replace(".xml", ".txt"))
  249. return -1;
  250. return None
  251. from parseCreditXmlModel import uploadJsonFile, uploadAudit