client_mongo_mysql_nzj_liantong.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # coding:utf-8
  2. import time
  3. from a2s.tools import json_serialize, json_deserialize
  4. from a2s.a2s_client import a2s_execute
  5. from docs.config import ReluMongodb
  6. from util.mogodb_helper import MongoDBInterface
  7. from pymongo import MongoClient
  8. from util.mysql_tool import MysqlUtil
  9. import json
  10. from datetime import datetime, timedelta
  11. from bson import ObjectId
  12. ReluClient = MongoDBInterface(ReluMongodb)
  13. # 评估服务配置
  14. a2s_ip = "172.20.100.235:9090"
  15. topic = "quality_bid"
  16. #本地测试用的主题
  17. # topic = "test_quality_bid"
  18. timeout = 300
  19. # 开始评估
  20. def start_quality(data: dict, rules_id: int, a2s_ip, topic, timeout, retry=3):
  21. # 本次不使用SSL,所以channel是不安全的
  22. row = {"data": data, "rules_id": rules_id}
  23. bytes_data = json_serialize(row)
  24. for t in range(retry):
  25. print("topic",topic)
  26. try:
  27. resp_data = a2s_execute(a2s_ip, topic, timeout, bytes_data)
  28. if resp_data is None:
  29. continue
  30. result = json_deserialize(resp_data)
  31. return result
  32. except Exception as e:
  33. print(e)
  34. return {}
  35. # 获取规则ID
  36. def get_rule(company, version):
  37. rule_id = ReluClient.find_rule_by_company(ReluMongodb["col"], company, version)
  38. return rule_id
  39. def find_error_id(conn, cleaned_key, sub_value):
  40. """
  41. 查找 error_dict 中的 id
  42. """
  43. query = """SELECT id FROM error_dict WHERE fields = %s AND error = %s"""
  44. params = (cleaned_key, sub_value)
  45. result = MysqlUtil.query_data(conn, query, params)
  46. #[(10,)]
  47. # 检查查询结果是否为空
  48. if not result:
  49. print(f"Error: No matching record found for fields={cleaned_key}, error={sub_value}")
  50. return None # 或者返回一个默认值,根据需求而定
  51. record = result[0][0]
  52. return record
  53. def insert_batch_data(conn, params):
  54. """
  55. 执行批量插入数据
  56. """
  57. query = """INSERT IGNORE INTO nzj_analysis_liantong (mongoid, area, city, district, score, error_type, create_time,
  58. projectname,title,owner,project_stage_code,capital)
  59. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )"""
  60. MysqlUtil.insert_data(conn, query, params)
  61. def insert_dynamic_error_field(conn, cleaned_key, error_ids, mongoid):
  62. """
  63. 动态插入 error_ids 到相应的 cleaned_key_error 字段
  64. """
  65. # 构造动态插入 SQL 语句,更新指定的 cleaned_key_error 字段
  66. query = f"""
  67. UPDATE nzj_analysis_liantong
  68. SET {cleaned_key}_error = %s
  69. WHERE mongoid = %s
  70. """
  71. # 拼接多个 error_id,用分隔符分开
  72. error_ids_str = ','.join(map(str, error_ids))
  73. params = (error_ids_str, mongoid )
  74. MysqlUtil.update_data(conn, query, params)
  75. def has_non_empty_qa(data):
  76. # 获取data字典
  77. data_dict = data.get('data', {})
  78. # 遍历所有键值对
  79. for key, value in data_dict.items():
  80. # 检查键以'_qa'结尾且值不为空
  81. if key.endswith('_qa') and value: # value不为None、空字典、空列表等
  82. return True
  83. return False
  84. def parse_timestamp(timestamp):
  85. if not timestamp:
  86. return None
  87. try:
  88. return datetime.fromtimestamp(int(timestamp))
  89. except (ValueError, TypeError):
  90. return None
  91. def insert_bid_statistics (col,conn,query,batch_id):
  92. # 定义来源 1标讯简版2拟在建3新闻4预算5专项债
  93. data_source = 2
  94. # 使用聚合管道进行多条件统计
  95. pipeline = [
  96. {"$match": query},
  97. {"$facet": {
  98. "总量": [{"$count": "count"}], # 添加总量统计
  99. }}
  100. ]
  101. result = list(col.aggregate(pipeline))[0]
  102. # 提取统计结果
  103. count_total = result["总量"][0]["count"] if result["总量"] else 0
  104. sql_query = """INSERT IGNORE INTO bid_statistics_liantong (nzj_count, batch_id, data_source )
  105. VALUES ( %s, %s, %s)"""
  106. params = (count_total,batch_id,data_source)
  107. MysqlUtil.insert_data(conn, sql_query, params)
  108. def batch_load_data():
  109. """
  110. 批量数据质量检查
  111. """
  112. # 获取今天的日期(字符串格式)
  113. today_date = datetime.now().strftime("%Y-%m-%d")
  114. yesterday_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
  115. # 获取昨天 00:00:00 的时间戳
  116. start_date = int(datetime.strptime(f"{yesterday_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  117. # print("start_date",start_date)
  118. # 获取今天 00:00:00 的时间戳
  119. end_date = int(datetime.strptime(f"{today_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  120. # print("end_date", end_date)
  121. # 规则查询,根据必要条件 公司名称(用户ID)、版本号
  122. rules_id = get_rule("中国联通-拟在建", "v1.4.4")
  123. print(rules_id)
  124. # 初始化mysql
  125. conn = MysqlUtil.connect_to_mysql(host='172.20.45.129', port='4000', user='root', password='=PDT49#80Z!RVv52_z',database='quality')
  126. max_id = ObjectId("0" * 24)
  127. # max_id = ObjectId("688363ebf0c6ad8b095e2245")
  128. # 查询条件:_id >= max_id, appid匹配,且 createtime 在 [start_date, end_date] 之间
  129. query = {
  130. "_id": {"$gte": max_id},
  131. # "_id": max_id,
  132. "createtime": {"$gte": start_date, "$lte": end_date}
  133. }
  134. # mongo_client = MongoClient('mongodb://127.0.0.1:27087/', unicode_decode_error_handler="ignore",directConnection=True) # 修改为你的连接地址
  135. mongo_client = MongoClient('mongodb://172.20.17.61:27080/', unicode_decode_error_handler="ignore",directConnection=True) # 正式环境
  136. client = mongo_client.jyqyfw
  137. coll_user = client["usermail_lt_nzj"]
  138. #存入数据总量,计算缺失率
  139. insert_bid_statistics(coll_user,conn,query,today_date)
  140. while True:
  141. try:
  142. for item in coll_user.find(query).sort("_id", 1):
  143. print("------数据处理开始--------")
  144. max_id = item["_id"]
  145. item["_id"] = str(item["_id"])
  146. print(f"正在处理数据: {max_id}")
  147. # 质量检查逻辑
  148. result = start_quality(item, rules_id, a2s_ip, topic, timeout)
  149. print(result)
  150. code = result.get("code")
  151. if code != 200:
  152. # 数据出错,跳过
  153. continue
  154. #只将有错误的数据存库
  155. if has_non_empty_qa(result):
  156. data = result.get("data", {})
  157. # 数据插入到 MySQL
  158. area = item.get("area", "")
  159. city = item.get("city", "")
  160. district = item.get("district", "")
  161. projectname =item.get('projectname',"")
  162. title = item.get("title", "")
  163. owner = item.get("owner", "")
  164. project_stage_code = item.get("project_stage_code", "")
  165. capital = item.get("capital","")
  166. # ---
  167. tenderlist = item.get("tenderlist", "")
  168. # publishtime = item.get("publishtime", "")
  169. # bidamount = item.get("bidamount", "")
  170. # projectcode = item.get("projectcode", "")
  171. # buyerperson = item.get("buyerperson", "")
  172. # buyertel = item.get("buyertel", "")
  173. # detail = item.get("detail", "")
  174. # href = item.get("href", "")
  175. # s_winner = item.get("s_winner", "")
  176. # winnerperson = item.get("winnerperson", "")
  177. # winnertel = item.get("winnertel", "")
  178. #---
  179. score = data.get("score", "")
  180. error_type_data = json.dumps(data)
  181. create_time = today_date
  182. params = (item["_id"], area, city, district, score, error_type_data,create_time, projectname, title, owner,project_stage_code,capital)
  183. insert_batch_data(conn, params)
  184. print("---- 数据处理完成 ----")
  185. break
  186. except Exception as e:
  187. print(f"错误: {e}")
  188. import traceback
  189. traceback.print_exc() # 打印完整堆栈信息
  190. time.sleep(10)
  191. finally:
  192. # 确保在循环结束后关闭连接
  193. conn.close() # 关闭MySQL连接
  194. mongo_client.close() # 关闭MongoDB连接
  195. if __name__ == '__main__':
  196. batch_load_data()