crowd_choose_offline_check.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # This is a sample Python script.
  2. # Press ⌃R to execute it or replace it with your code.
  3. # Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
  4. import hashlib
  5. import json
  6. import os
  7. import subprocess
  8. import time
  9. import traceback
  10. import urllib
  11. import datetime
  12. import requests
  13. import pymysql
  14. from contextlib import contextmanager
  15. from sqlalchemy import create_engine, Numeric, Float
  16. from sqlalchemy.orm import sessionmaker
  17. from sqlalchemy.ext.declarative import declarative_base
  18. from sqlalchemy import Column, Integer, String, DateTime, Text
  19. import ssl
  20. ssl._create_default_https_context = ssl._create_unverified_context
  21. HOST = 'rm-bp1nx318263k95yo3318.mysql.rds.aliyuncs.com'
  22. PORT = '3306'
  23. DATABASE = 'uservideo_bi'
  24. USERNAME = 'majin'
  25. PASSWORD = 'E5d2c960fdf3f5f0be5a27eea2f906ef'
  26. DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,
  27. password=PASSWORD,
  28. host=HOST, port=PORT,
  29. db=DATABASE)
  30. # HOST = 'rm-bp1k5853td1r25g3n690.mysql.rds.aliyuncs.com'
  31. # PORT = '3306'
  32. # DATABASE = 'mpad'
  33. # USERNAME = 'majin'
  34. # PASSWORD = 'e5d2c960fdf3f5f0be5a27eea2f906ef'
  35. # DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,
  36. # password=PASSWORD,
  37. # host=HOST, port=PORT,
  38. # db=DATABASE)
  39. Base = declarative_base()
  40. class WECHAT_AD_PUBLISHER_ADUNIT_GENERAL(Base):
  41. __tablename__ = 'wechat_ad_publisher_adunit_general'
  42. id = Column(Integer, primary_key=True)
  43. ad_unit_id = Column(String(1000))
  44. ad_unit_name = Column(String(1000))
  45. ad_slot = Column(String(1000))
  46. click_count = Column(Integer, default=0)
  47. click_rate = Column(Float, default=0.0)
  48. date = Column(String(1000))
  49. ecpm = Column(String(1000))
  50. exposure_count = Column(Integer, default=0)
  51. exposure_rate = Column(Float, default=0.0)
  52. income = Column(Integer, default=0)
  53. req_succ_count = Column(Integer, default=0)
  54. app_type = Column(Integer, default=0)
  55. slot_str = Column(String(1000))
  56. date_str = Column(String(1000))
  57. def __init__(self):
  58. print(f"AUNIT_GENERAL.init app_type = {self.app_type}, ad_unit_id = {self.ad_unit_id}")
  59. def __repr__(self):
  60. return '<WECHAT_AD_PUBLISHER_ADUNIT_GENERAL %r>' % self.ad_unit_id
  61. class WECHAT_AD_PUBLISHER_ADPOS_GENERAL(Base):
  62. __tablename__ = 'wechat_ad_publisher_adpos_general'
  63. id = Column(Integer, primary_key=True)
  64. ad_slot = Column(String(1000))
  65. click_count = Column(Integer, default=0)
  66. click_rate = Column(Float, default=0.0)
  67. date = Column(String(1000))
  68. ecpm = Column(String(1000))
  69. exposure_count = Column(Integer, default=0)
  70. exposure_rate = Column(Float, default=0.0)
  71. income = Column(Integer, default=0)
  72. req_succ_count = Column(Integer, default=0)
  73. app_type = Column(Integer, default=0)
  74. slot_str = Column(String(1000))
  75. date_str = Column(String(1000))
  76. def __init__(self):
  77. print(f"ADPOS_GENERAL.init app_type = {self.app_type}, ad_slot = {self.ad_slot}")
  78. def __repr__(self):
  79. return '<wechat_ad_publisher_adpos_general %r>' % self.ad_slot
  80. @contextmanager
  81. def session_maker(session=None, session_factory=None):
  82. try:
  83. if session_factory is None:
  84. engine = create_engine(DB_URI)
  85. session_factory = sessionmaker(bind=engine)
  86. if session is None:
  87. session = session_factory()
  88. yield session
  89. except:
  90. session.rollback()
  91. raise
  92. else:
  93. session.commit()
  94. # logger.debug('session.commit(){}'.format(session))
  95. finally:
  96. session.close()
  97. # logger.debug('session.close(){}'.format(session))
  98. def add_ad_data(data, app_type):
  99. # Use a breakpoint in the code line below to debug your script.
  100. print(f'Hi, add_ad_data.app_type = {app_type}, data = {data}') # Press ⌘F8 to toggle the breakpoint.
  101. stat_item = data['stat_item']
  102. try:
  103. with session_maker() as session:
  104. wechat_ad_publisher_adunit_general = WECHAT_AD_PUBLISHER_ADUNIT_GENERAL()
  105. wechat_ad_publisher_adunit_general.ad_unit_id = data['ad_unit_id']
  106. wechat_ad_publisher_adunit_general.ad_unit_name = data['ad_unit_name']
  107. wechat_ad_publisher_adunit_general.ad_slot = stat_item['ad_slot']
  108. wechat_ad_publisher_adunit_general.click_count = stat_item['click_count']
  109. wechat_ad_publisher_adunit_general.click_rate = stat_item['click_rate']
  110. wechat_ad_publisher_adunit_general.date = stat_item['date']
  111. wechat_ad_publisher_adunit_general.ecpm = stat_item['ecpm']
  112. wechat_ad_publisher_adunit_general.exposure_count = stat_item['exposure_count']
  113. wechat_ad_publisher_adunit_general.exposure_rate = stat_item['exposure_rate']
  114. wechat_ad_publisher_adunit_general.income = stat_item['income']
  115. wechat_ad_publisher_adunit_general.req_succ_count = stat_item['req_succ_count']
  116. wechat_ad_publisher_adunit_general.slot_str = stat_item['slot_str']
  117. wechat_ad_publisher_adunit_general.date_str = stat_item['date'].replace('-','')
  118. wechat_ad_publisher_adunit_general.app_type = app_type
  119. session.add(wechat_ad_publisher_adunit_general)
  120. print(f'add_ad_data is OK!; app_type = {app_type}')
  121. except Exception as e:
  122. traceback.print_exc()
  123. print(f"add_ad_data error: app_type = {app_type}; traceback.format_exc = {traceback.format_exc()}")
  124. def add_ad_adpos_data(stat_item, app_type):
  125. # Use a breakpoint in the code line below to debug your script.
  126. print(f'Hi, add_ad_adpos_data.app_type = {app_type}, stat_time = {stat_item}') # Press ⌘F8 to toggle the breakpoint.
  127. try:
  128. with session_maker() as session:
  129. wechat_ad_publisher_adpos_general = WECHAT_AD_PUBLISHER_ADPOS_GENERAL()
  130. wechat_ad_publisher_adpos_general.ad_slot = stat_item['ad_slot']
  131. wechat_ad_publisher_adpos_general.click_count = stat_item['click_count']
  132. wechat_ad_publisher_adpos_general.click_rate = stat_item['click_rate']
  133. wechat_ad_publisher_adpos_general.date = stat_item['date']
  134. wechat_ad_publisher_adpos_general.ecpm = stat_item['ecpm']
  135. wechat_ad_publisher_adpos_general.exposure_count = stat_item['exposure_count']
  136. wechat_ad_publisher_adpos_general.exposure_rate = stat_item['exposure_rate']
  137. wechat_ad_publisher_adpos_general.income = stat_item['income']
  138. wechat_ad_publisher_adpos_general.req_succ_count = stat_item['req_succ_count']
  139. wechat_ad_publisher_adpos_general.slot_str = stat_item['slot_str']
  140. wechat_ad_publisher_adpos_general.date_str = stat_item['date'].replace('-','')
  141. wechat_ad_publisher_adpos_general.app_type = app_type
  142. session.add(wechat_ad_publisher_adpos_general)
  143. print(f'add_ad_adpos_data is OK; app_type = {app_type}')
  144. except Exception as e:
  145. traceback.print_exc()
  146. print(f"add_ad_adpos_data error: app_type = {app_type}; traceback.format_exc = {traceback.format_exc()}")
  147. def post_inform(url, content_text):
  148. url = url
  149. data = json.dumps(content_text)
  150. data = bytes(data, 'utf8')
  151. print(f"post_inform data = {data}")
  152. headers = {"Content-Type": 'application/json'}
  153. req = urllib.request.Request(url=url, headers=headers, data=data)
  154. try:
  155. resp = urllib.request.urlopen(req, timeout=10).read()
  156. print(f"post_inform resp = {resp.decode('utf-8')}")
  157. return resp.decode('utf-8')
  158. except Exception as e:
  159. print(e)
  160. def get_inform(url):
  161. url = url
  162. headers = {"Content-Type": 'application/json'}
  163. print(f"get_inform url = {url}")
  164. req = urllib.request.Request(url=url, headers=headers)
  165. try:
  166. resp = urllib.request.urlopen(req, timeout=10).read()
  167. print(f"get_inform resp = {resp.decode('utf-8')}")
  168. return resp.decode('utf-8')
  169. except Exception as e:
  170. print(e)
  171. def get_mp_info(app_type):
  172. datestr = datetime.datetime.strftime(datetime.datetime.now() - datetime.timedelta(days=+1), '%Y-%m-%d')
  173. print(f"get_mp_info: app_type = {app_type} date = {datestr}")
  174. time_str = time.strftime("%Y:%m:%d %H")
  175. print(f"get_mp_info: app_type= {app_type} time = {time_str}")
  176. md5 = hashlib.md5('{}'.format(time_str).encode(encoding='UTF-8')).hexdigest()
  177. print(f"get_mp_info: app_type = {app_type} md5 = {md5}")
  178. getliveaccesstoken_url = "https://longvideoapi.piaoquantv.com/longvideoapi/weixin/getWxAccessToken/{}".format(app_type)
  179. print(f"get_mp_info getliveaccesstoken_url = {getliveaccesstoken_url}")
  180. ret = get_inform(getliveaccesstoken_url)
  181. data = json.loads(ret).get('data',{})
  182. print(f"get_mp_info app_type = {app_type} getWxAccessToken date = {data}")
  183. with session_maker() as session:
  184. task = session.query(WECHAT_AD_PUBLISHER_ADUNIT_GENERAL).filter_by(date=datestr,app_type=app_type).first()
  185. if task is None:
  186. getweanalysisappiddailyvisittrend_url = 'https://api.weixin.qq.com/publisher/stat?action=publisher_adunit_general&access_token={}&page=1&page_size=100&start_date={}&end_date={}'.format(
  187. data, datestr, datestr)
  188. print(f"get_mp_info app_type = {app_type} publisher/stat adunit = {getweanalysisappiddailyvisittrend_url}")
  189. ret = get_inform(getweanalysisappiddailyvisittrend_url)
  190. print(f"get_mp_info app_type = {app_type} publisher/stat adunit result = {ret}")
  191. list = json.loads(ret).get('list',[])
  192. for item in list:
  193. add_ad_data(item, app_type)
  194. task = session.query(WECHAT_AD_PUBLISHER_ADPOS_GENERAL).filter_by(date=datestr, app_type=app_type).first()
  195. if task is None:
  196. getweanalysisappiddailyvisittrend_url = 'https://api.weixin.qq.com/publisher/stat?action=publisher_adpos_general&access_token={}&page=1&page_size=100&start_date={}&end_date={}'.format(
  197. data, datestr, datestr)
  198. print(f"get_mp_info app_type = {app_type} publisher/stat adops = {getweanalysisappiddailyvisittrend_url}")
  199. ret = get_inform(getweanalysisappiddailyvisittrend_url)
  200. print(f"get_mp_info app_type = {app_type} publisher/stat adops result = {ret}")
  201. list = json.loads(ret).get('list',[])
  202. for item in list:
  203. add_ad_adpos_data(item, app_type)
  204. summary = json.loads(ret)['summary']
  205. summary['ad_slot'] = 'SLOT_ID_WEAPP_ALL'
  206. summary['date'] = datestr
  207. summary['slot_str'] = 'summary'
  208. add_ad_adpos_data(summary, app_type)
  209. # Press the green button in the gutter to run the script.
  210. if __name__ == '__main__':
  211. app_type_list = [0,2,3,4,5,6,17,18,19,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]
  212. # app_type_list = [2,23,24,25]
  213. for app_type in app_type_list:
  214. print(f"start app_type = {app_type}")
  215. try:
  216. get_mp_info(app_type)
  217. except Exception as e:
  218. print(f"app_type {app_type} get data error: {traceback.format_exc()}")
  219. print(f"end app_type = {app_type}")
  220. print("")
  221. # See PyCharm help at https://www.jetbrains.com/help/pycharm/