client_mongo_mysql_nzj_liantong.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 batch_load_data():
  92. """
  93. 批量数据质量检查
  94. """
  95. # 获取今天的日期(字符串格式)
  96. today_date = datetime.now().strftime("%Y-%m-%d")
  97. yesterday_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
  98. # 获取昨天 00:00:00 的时间戳
  99. start_date = int(datetime.strptime(f"{yesterday_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  100. # print("start_date",start_date)
  101. # 获取今天 00:00:00 的时间戳
  102. end_date = int(datetime.strptime(f"{today_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  103. # print("end_date", end_date)
  104. # 规则查询,根据必要条件 公司名称(用户ID)、版本号
  105. rules_id = get_rule("中国联通-拟在建", "v1.4.4")
  106. print(rules_id)
  107. # 初始化mysql
  108. conn = MysqlUtil.connect_to_mysql(host='172.20.45.129', port='4000', user='root', password='=PDT49#80Z!RVv52_z',database='quality')
  109. max_id = ObjectId("0" * 24)
  110. # max_id = ObjectId("688363ebf0c6ad8b095e2245")
  111. # 查询条件:_id >= max_id, appid匹配,且 createtime 在 [start_date, end_date] 之间
  112. query = {
  113. "_id": {"$gte": max_id},
  114. # "_id": max_id,
  115. # "appid": "jyGQ1XQQsEAwNeSENOFR9D",
  116. # "createtime": {"$gte": start_date, "$lte": end_date}
  117. }
  118. while True:
  119. # client = MongoClient('mongodb://127.0.0.1:27087/', unicode_decode_error_handler="ignore",directConnection=True).jyqyfw # 修改为你的连接地址
  120. client = MongoClient('mongodb://172.20.17.61:27080/', unicode_decode_error_handler="ignore",directConnection=True).jyqyfw # 正式环境
  121. coll_user = client["usermail_lt_nzj"]
  122. try:
  123. for item in coll_user.find(query).sort("_id", 1):
  124. print("------数据处理开始--------")
  125. max_id = item["_id"]
  126. item["_id"] = str(item["_id"])
  127. print(f"正在处理数据: {max_id}")
  128. # 质量检查逻辑
  129. result = start_quality(item, rules_id, a2s_ip, topic, timeout)
  130. print(result)
  131. code = result.get("code")
  132. if code != 200:
  133. # 数据出错,跳过
  134. continue
  135. #只将有错误的数据存库
  136. if has_non_empty_qa(result):
  137. data = result.get("data", {})
  138. # 数据插入到 MySQL
  139. area = item.get("area", "")
  140. city = item.get("city", "")
  141. district = item.get("district", "")
  142. projectname =item.get('projectname',"")
  143. title = item.get("title", "")
  144. owner = item.get("owner", "")
  145. project_stage_code = item.get("project_stage_code", "")
  146. capital = item.get("capital","")
  147. # ---
  148. tenderlist = item.get("tenderlist", "")
  149. # publishtime = item.get("publishtime", "")
  150. # bidamount = item.get("bidamount", "")
  151. # projectcode = item.get("projectcode", "")
  152. # buyerperson = item.get("buyerperson", "")
  153. # buyertel = item.get("buyertel", "")
  154. # detail = item.get("detail", "")
  155. # href = item.get("href", "")
  156. # s_winner = item.get("s_winner", "")
  157. # winnerperson = item.get("winnerperson", "")
  158. # winnertel = item.get("winnertel", "")
  159. #---
  160. score = data.get("score", "")
  161. error_type_data = json.dumps(data)
  162. create_time = today_date
  163. params = (item["_id"], area, city, district, score, error_type_data,create_time, projectname, title, owner,project_stage_code,capital)
  164. insert_batch_data(conn, params)
  165. print("---- 数据处理完成 ----")
  166. break
  167. except Exception as e:
  168. print(f"错误: {e}")
  169. import traceback
  170. traceback.print_exc() # 打印完整堆栈信息
  171. time.sleep(10)
  172. if __name__ == '__main__':
  173. batch_load_data()