updateAccountV3.py 7.8 KB

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