updateAccountV3.py 7.6 KB

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