client_mongo_mysql_liantong.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 = 180
  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 bid_analysis_liantong (mongoid,toptype,subtype, site, spidercode, channel,comeintime, area, city, district, score, error_type, create_time)
  58. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s,%s,%s)"""
  59. MysqlUtil.insert_data(conn, query, params)
  60. def insert_dynamic_error_field(conn, cleaned_key, error_ids, mongoid):
  61. """
  62. 动态插入 error_ids 到相应的 cleaned_key_error 字段
  63. """
  64. # 构造动态插入 SQL 语句,更新指定的 cleaned_key_error 字段
  65. query = f"""
  66. UPDATE bid_analysis_liantong
  67. SET {cleaned_key}_error = %s
  68. WHERE mongoid = %s
  69. """
  70. # 拼接多个 error_id,用分隔符分开
  71. error_ids_str = ','.join(map(str, error_ids))
  72. params = (error_ids_str, mongoid )
  73. MysqlUtil.update_data(conn, query, params)
  74. def has_non_empty_qa(data):
  75. # 获取data字典
  76. data_dict = data.get('data', {})
  77. # 遍历所有键值对
  78. for key, value in data_dict.items():
  79. # 检查键以'_qa'结尾且值不为空
  80. if key.endswith('_qa') and value: # value不为None、空字典、空列表等
  81. return True
  82. return False
  83. def batch_load_data():
  84. """
  85. 批量数据质量检查
  86. """
  87. # 获取今天的日期(字符串格式)
  88. today_date = datetime.now().strftime("%Y-%m-%d")
  89. yesterday_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
  90. # 获取昨天 00:00:00 的时间戳
  91. start_date = int(datetime.strptime(f"{yesterday_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  92. # print("start_date",start_date)
  93. # 获取今天 00:00:00 的时间戳
  94. end_date = int(datetime.strptime(f"{today_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  95. # print("end_date", end_date)
  96. # 规则查询,根据必要条件 公司名称(用户ID)、版本号
  97. rules_id = get_rule("北京剑鱼信息技术有限公司", "v1.3")
  98. print(rules_id)
  99. # 初始化mysql
  100. conn = MysqlUtil.connect_to_mysql(host='172.20.45.129', port='4000', user='root', password='=PDT49#80Z!RVv52_z',database='quality')
  101. max_id = ObjectId("0" * 24)
  102. # max_id = ObjectId("6881072ff0c6ad8b095d808e")
  103. # 查询条件:_id >= max_id, appid匹配,且 createtime 在 [start_date, end_date] 之间
  104. query = {
  105. "_id": {"$gte": max_id},
  106. # "_id": max_id,
  107. "appid": "jyGQ1XQQsEAwNeSENOFR9D",
  108. "createtime": {"$gte": start_date, "$lte": end_date}
  109. }
  110. while True:
  111. client = MongoClient('mongodb://127.0.0.1:27087/', unicode_decode_error_handler="ignore",directConnection=True).jyqyfw # 修改为你的连接地址
  112. coll_user = client["usermail"]
  113. try:
  114. for item in coll_user.find(query).sort("_id", 1):
  115. print("------数据处理开始--------")
  116. max_id = item["_id"]
  117. item["_id"] = str(item["_id"])
  118. print(f"正在处理数据: {max_id}")
  119. # 质量检查逻辑
  120. result = start_quality(item, rules_id, a2s_ip, topic, timeout)
  121. print(result)
  122. code = result.get("code")
  123. if code != 200:
  124. # 数据出错,跳过
  125. continue
  126. #只将有错误的数据存库
  127. if has_non_empty_qa(result):
  128. data = result.get("data", {})
  129. # 数据插入到 MySQL
  130. toptype = item.get("toptype", "")
  131. subtype = item.get("subtype", "")
  132. site = item.get("site", "")
  133. spidercode = item.get("spidercode", "")
  134. channel = item.get("channel", "")
  135. comeintime = item.get("comeintime", "")
  136. comeintime = datetime.fromtimestamp(comeintime)
  137. area = item.get("area", "")
  138. city = item.get("city", "")
  139. district = item.get("district", "")
  140. score = item.get("score", "")
  141. error_type_data = json.dumps(data)
  142. create_time = today_date
  143. params = (item["_id"], toptype, subtype, site, spidercode,channel, comeintime, area, city, district, score, error_type_data,create_time)
  144. insert_batch_data(conn, params)
  145. print("---- 数据处理完成 ----")
  146. break
  147. except Exception as e:
  148. print(f"错误: {e}")
  149. time.sleep(10)
  150. if __name__ == '__main__':
  151. batch_load_data()