client_mongo_mysql_liantong.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 bid_analysis_liantong (mongoid,toptype,subtype, site, spidercode, channel,comeintime, area, city, district, score, error_type, create_time,
  58. agency,agencyperson,agencytel,bidamount,bidendtime,bidopentime,bidstarttime,bidway,budget,buyer,buyerperson,buyertel,com_package,docendtime,
  59. docstarttime,est_purchase_time,href,projectcode,projectname,publishtime,s_winner,title,winnerorder,winnerperson,winnertel)
  60. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
  61. MysqlUtil.insert_data(conn, query, params)
  62. def insert_dynamic_error_field(conn, cleaned_key, error_ids, mongoid):
  63. """
  64. 动态插入 error_ids 到相应的 cleaned_key_error 字段
  65. """
  66. # 构造动态插入 SQL 语句,更新指定的 cleaned_key_error 字段
  67. query = f"""
  68. UPDATE bid_analysis_liantong
  69. SET {cleaned_key}_error = %s
  70. WHERE mongoid = %s
  71. """
  72. # 拼接多个 error_id,用分隔符分开
  73. error_ids_str = ','.join(map(str, error_ids))
  74. params = (error_ids_str, mongoid )
  75. MysqlUtil.update_data(conn, query, params)
  76. def has_non_empty_qa(data):
  77. # 获取data字典
  78. data_dict = data.get('data', {})
  79. # 遍历所有键值对
  80. for key, value in data_dict.items():
  81. # 检查键以'_qa'结尾且值不为空
  82. if key.endswith('_qa') and value: # value不为None、空字典、空列表等
  83. return True
  84. return False
  85. def parse_timestamp(timestamp):
  86. if not timestamp:
  87. return None
  88. try:
  89. return datetime.fromtimestamp(int(timestamp))
  90. except (ValueError, TypeError):
  91. return None
  92. def batch_load_data():
  93. """
  94. 批量数据质量检查
  95. """
  96. # 获取今天的日期(字符串格式)
  97. today_date = datetime.now().strftime("%Y-%m-%d")
  98. yesterday_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
  99. # 获取昨天 00:00:00 的时间戳
  100. start_date = int(datetime.strptime(f"{yesterday_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  101. # print("start_date",start_date)
  102. # 获取今天 00:00:00 的时间戳
  103. end_date = int(datetime.strptime(f"{today_date} 00:00:00", "%Y-%m-%d %H:%M:%S").timestamp())
  104. # print("end_date", end_date)
  105. # 规则查询,根据必要条件 公司名称(用户ID)、版本号
  106. rules_id = get_rule("中国联通", "v1.3")
  107. print(rules_id)
  108. # 初始化mysql
  109. conn = MysqlUtil.connect_to_mysql(host='172.20.45.129', port='4000', user='root', password='=PDT49#80Z!RVv52_z',database='quality')
  110. max_id = ObjectId("0" * 24)
  111. # max_id = ObjectId("688363ebf0c6ad8b095e2245")
  112. # 查询条件:_id >= max_id, appid匹配,且 createtime 在 [start_date, end_date] 之间
  113. query = {
  114. "_id": {"$gte": max_id},
  115. # "_id": max_id,
  116. "appid": "jyGQ1XQQsEAwNeSENOFR9D",
  117. "createtime": {"$gte": start_date, "$lte": end_date}
  118. }
  119. while True:
  120. client = MongoClient('mongodb://127.0.0.1:27087/', unicode_decode_error_handler="ignore",directConnection=True).jyqyfw # 修改为你的连接地址
  121. # client = MongoClient('mongodb://172.20.17.61:27080/', unicode_decode_error_handler="ignore",directConnection=True).jyqyfw # 正式环境
  122. coll_user = client["usermail"]
  123. try:
  124. for item in coll_user.find(query).sort("_id", 1):
  125. print("------数据处理开始--------")
  126. max_id = item["_id"]
  127. item["_id"] = str(item["_id"])
  128. print(f"正在处理数据: {max_id}")
  129. # 质量检查逻辑
  130. result = start_quality(item, rules_id, a2s_ip, topic, timeout)
  131. print(result)
  132. code = result.get("code")
  133. if code != 200:
  134. # 数据出错,跳过
  135. continue
  136. #只将有错误的数据存库
  137. if has_non_empty_qa(result):
  138. data = result.get("data", {})
  139. # 数据插入到 MySQL
  140. toptype = item.get("toptype", "")
  141. subtype = item.get("subtype", "")
  142. site = item.get("site", "")
  143. spidercode = item.get("spidercode", "")
  144. channel = item.get("channel", "")
  145. comeintime = item.get("comeintime", "")
  146. comeintime = datetime.fromtimestamp(comeintime)
  147. area = item.get("area", "")
  148. city = item.get("city", "")
  149. district = item.get("district", "")
  150. #---
  151. agency = item.get("agency", "")
  152. agencyperson = item.get("agencyperson", "")
  153. agencytel = item.get("agencytel", "")
  154. bidamount = item.get("bidamount", "")
  155. bidendtime = item.get("bidendtime", "")
  156. bidendtime = parse_timestamp(bidendtime)
  157. bidopentime = item.get("bidopentime", "")
  158. bidopentime = parse_timestamp(bidopentime)
  159. bidstarttime = item.get("bidstarttime", "")
  160. bidstarttime = parse_timestamp(bidstarttime)
  161. bidway = item.get("bidway", "")
  162. budget = item.get("budget", "")
  163. buyer = item.get("buyer", "")
  164. buyerperson = item.get("buyerperson", "")
  165. buyertel = item.get("buyertel", "")
  166. com_package = item.get("com_package", "") #json串
  167. com_package =json.dumps(com_package)
  168. docendtime = item.get("docendtime", "")
  169. docendtime = parse_timestamp(docendtime)
  170. docstarttime = item.get("docstarttime", "")
  171. docstarttime = parse_timestamp(docstarttime)
  172. est_purchase_time = item.get("est_purchase_time", "")
  173. est_purchase_time = parse_timestamp(est_purchase_time)
  174. href = item.get("href", "")
  175. projectcode = item.get("projectcode", "")
  176. projectname = item.get("projectname", "")
  177. publishtime = item.get("publishtime", "")
  178. publishtime = parse_timestamp(publishtime)
  179. s_winner = item.get("s_winner", "")
  180. title = item.get("title", "")
  181. winnerorder = item.get("winnerorder", "")#json串
  182. winnerorder = json.dumps(winnerorder)
  183. winnerperson = item.get("winnerperson", "")
  184. winnertel = item.get("winnertel", "")
  185. #---
  186. score = data.get("score", "")
  187. error_type_data = json.dumps(data)
  188. create_time = today_date
  189. params = (item["_id"], toptype, subtype, site, spidercode,channel, comeintime, area, city, district, score, error_type_data,create_time,
  190. agency,agencyperson,agencytel,bidamount,bidendtime,bidopentime,bidstarttime,bidway,budget,buyer,buyerperson,buyertel,com_package,docendtime,
  191. docstarttime,est_purchase_time,href,projectcode,projectname,publishtime,s_winner,title,winnerorder,winnerperson,winnertel)
  192. insert_batch_data(conn, params)
  193. print("---- 数据处理完成 ----")
  194. break
  195. except Exception as e:
  196. print(f"错误: {e}")
  197. import traceback
  198. traceback.print_exc() # 打印完整堆栈信息
  199. time.sleep(10)
  200. if __name__ == '__main__':
  201. batch_load_data()