updateAccountV3.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """
  2. @author: luojunhui
  3. """
  4. import json
  5. import time
  6. from tqdm import tqdm
  7. from datetime import datetime, timedelta
  8. from argparse import ArgumentParser
  9. from applications import PQMySQL, DeNetMysql, longArticlesMySQL
  10. from applications.const import updateAccountReadAvgTaskConst
  11. from config import apolloConfig
  12. config = apolloConfig()
  13. unauthorized_account = json.loads(config.getConfigValue("unauthorized_gh_id_fans"))
  14. touliu_accounts = set(json.loads(config.getConfigValue("touliu_gh_id_list")))
  15. def get_account_fans_by_dt(db_client) -> dict:
  16. """
  17. 获取每个账号发粉丝,通过日期来区分
  18. :return:
  19. """
  20. sql = f"""
  21. SELECT
  22. t1.date_str,
  23. t1.fans_count,
  24. t2.gh_id
  25. FROM datastat_wx t1
  26. JOIN publish_account t2 ON t1.account_id = t2.id
  27. WHERE
  28. t2.channel = 5
  29. AND t2.status = 1
  30. AND t1.date_str >= '2024-09-01'
  31. ORDER BY t1.date_str;
  32. """
  33. result = db_client.select(sql)
  34. D = {}
  35. for line in result:
  36. dt = line[0]
  37. fans = line[1]
  38. gh_id = line[2]
  39. if D.get(gh_id):
  40. D[gh_id][dt] = fans
  41. else:
  42. D[gh_id] = {dt: fans}
  43. return D
  44. class UpdateAccountInfoVersion3(object):
  45. """
  46. 更新账号信息 v3
  47. """
  48. def __init__(self):
  49. self.const = updateAccountReadAvgTaskConst()
  50. self.pq = PQMySQL()
  51. self.de = DeNetMysql()
  52. self.lam = longArticlesMySQL()
  53. def get_account_position_read_rate(self, dt):
  54. """
  55. 从长文数据库获取账号阅读均值
  56. :return:
  57. """
  58. dt = int(dt.replace("-", ""))
  59. sql = f"""
  60. SELECT
  61. gh_id, position, read_rate_avg
  62. FROM
  63. long_articles_read_rate
  64. WHERE dt_version = {dt};
  65. """
  66. result = self.lam.select(sql)
  67. account_read_rate_dict = {}
  68. for item in result:
  69. gh_id = item[0]
  70. position = item[1]
  71. rate = item[2]
  72. key = "{}_{}".format(gh_id, position)
  73. account_read_rate_dict[key] = rate
  74. return account_read_rate_dict
  75. def get_publishing_accounts(self):
  76. """
  77. 获取每日正在发布的账号
  78. :return:
  79. """
  80. sql = f"""
  81. SELECT DISTINCT
  82. t3.`name`,
  83. t3.gh_id,
  84. t3.follower_count,
  85. t6.account_source_name,
  86. t6.mode_type,
  87. t6.account_type,
  88. t6.`status`
  89. FROM
  90. publish_plan t1
  91. JOIN publish_plan_account t2 ON t1.id = t2.plan_id
  92. JOIN publish_account t3 ON t2.account_id = t3.id
  93. LEFT JOIN publish_account_wx_type t4 on t3.id = t4.account_id
  94. LEFT JOIN wx_statistics_group_source_account t5 on t3.id = t5.account_id
  95. LEFT JOIN wx_statistics_group_source t6 on t5.group_source_name = t6.account_source_name
  96. WHERE
  97. t1.plan_status = 1
  98. AND t3.channel = 5
  99. GROUP BY t3.id;
  100. """
  101. account_list = self.de.select(sql)
  102. result_list = [
  103. {
  104. "account_name": i[0],
  105. "gh_id": i[1],
  106. "fans": i[2],
  107. "account_source_name": i[3],
  108. "mode_type": i[4],
  109. "account_type": i[5],
  110. "status": i[6]
  111. } for i in account_list
  112. ]
  113. return result_list
  114. def do_task_list(self, dt):
  115. """
  116. do it
  117. """
  118. fans_dict = get_account_fans_by_dt(db_client=self.de)
  119. account_list = self.get_publishing_accounts()
  120. rate_dict = self.get_account_position_read_rate(dt)
  121. for account in tqdm(account_list, desc=dt):
  122. gh_id = account["gh_id"]
  123. business_type = self.const.TOULIU if gh_id in touliu_accounts else self.const.ARTICLES_DAILY
  124. fans = fans_dict.get(gh_id, {}).get(dt, 0)
  125. if not fans:
  126. fans = int(unauthorized_account.get(gh_id, 0))
  127. if fans:
  128. for index in range(1, 9):
  129. gh_id_position = "{}_{}".format(gh_id, index)
  130. if rate_dict.get(gh_id_position):
  131. rate = rate_dict[gh_id_position]
  132. read_avg = fans * rate
  133. print(rate, read_avg)
  134. insert_sql = f"""
  135. INSERT INTO account_avg_info_v3
  136. (gh_id, position, update_time, account_name, fans, read_avg, like_avg, status, account_type, account_mode, account_source, account_status, business_type, read_rate_avg)
  137. values
  138. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  139. """
  140. try:
  141. self.pq.update(
  142. sql=insert_sql,
  143. params=(
  144. gh_id,
  145. index,
  146. dt,
  147. account['account_name'],
  148. fans,
  149. read_avg,
  150. 0,
  151. 1,
  152. account['account_type'],
  153. account['mode_type'],
  154. account['account_source_name'],
  155. account['status'],
  156. business_type,
  157. rate
  158. )
  159. )
  160. except Exception as e:
  161. updateSQL = f"""
  162. UPDATE account_avg_info_v3
  163. set fans = %s, read_avg = %s, read_rate_avg = %s
  164. where gh_id = %s and position = %s and update_time = %s
  165. """
  166. try:
  167. affected_rows = self.pq.update(
  168. sql=updateSQL,
  169. params=(
  170. fans,
  171. read_avg,
  172. rate,
  173. account['gh_id'],
  174. index,
  175. dt
  176. )
  177. )
  178. except Exception as e:
  179. print(e)
  180. # 修改前一天的状态为 0
  181. update_status_sql = f"""
  182. UPDATE account_avg_info_v3
  183. SET status = %s
  184. where update_time != %s and gh_id = %s and position = %s;
  185. """
  186. rows_affected = self.pq.update(
  187. sql=update_status_sql,
  188. params=(
  189. 0, dt, account['gh_id'], index
  190. )
  191. )
  192. print("修改成功")
  193. def main():
  194. """
  195. main job
  196. :return:
  197. """
  198. parser = ArgumentParser()
  199. parser.add_argument("--run-date",
  200. help="Run only once for date in format of %Y-%m-%d. \
  201. If no specified, run as daily jobs.")
  202. args = parser.parse_args()
  203. Up = UpdateAccountInfoVersion3()
  204. if args.run_date:
  205. Up.do_task_list(dt=args.run_date)
  206. else:
  207. dt_object = datetime.fromtimestamp(int(time.time()))
  208. one_day = timedelta(days=1)
  209. yesterday = dt_object - one_day
  210. yesterday_str = yesterday.strftime('%Y-%m-%d')
  211. Up.do_task_list(dt=yesterday_str)
  212. if __name__ == '__main__':
  213. main()