mpad.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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(self.ad_unit_id)
  59. #print("app_type = "+ app_type +" adunit_id = "+self.ad_unit_id)
  60. def __repr__(self):
  61. return '<WECHAT_AD_PUBLISHER_ADUNIT_GENERAL %r>' % self.ad_unit_id
  62. class WECHAT_AD_PUBLISHER_ADPOS_GENERAL(Base):
  63. __tablename__ = 'wechat_ad_publisher_adpos_general'
  64. id = Column(Integer, primary_key=True)
  65. ad_slot = Column(String(1000))
  66. click_count = Column(Integer, default=0)
  67. click_rate = Column(Float, default=0.0)
  68. date = Column(String(1000))
  69. ecpm = Column(String(1000))
  70. exposure_count = Column(Integer, default=0)
  71. exposure_rate = Column(Float, default=0.0)
  72. income = Column(Integer, default=0)
  73. req_succ_count = Column(Integer, default=0)
  74. app_type = Column(Integer, default=0)
  75. slot_str = Column(String(1000))
  76. date_str = Column(String(1000))
  77. def __init__(self):
  78. print(self.ad_slot)
  79. #print("app_type = "+app_type+" ad_solt = "+self.ad_slot)
  80. def __repr__(self):
  81. return '<wechat_ad_publisher_adpos_general %r>' % self.ad_slot
  82. @contextmanager
  83. def session_maker(session=None, session_factory=None):
  84. try:
  85. if session_factory is None:
  86. engine = create_engine(DB_URI)
  87. session_factory = sessionmaker(bind=engine)
  88. if session is None:
  89. session = session_factory()
  90. yield session
  91. except:
  92. session.rollback()
  93. raise
  94. else:
  95. session.commit()
  96. # logger.debug('session.commit(){}'.format(session))
  97. finally:
  98. session.close()
  99. # logger.debug('session.close(){}'.format(session))
  100. def add_ad_data(data, app_type):
  101. # Use a breakpoint in the code line below to debug your script.
  102. print(f'Hi, {data}') # Press ⌘F8 to toggle the breakpoint.
  103. stat_item = data['stat_item']
  104. try:
  105. with session_maker() as session:
  106. wechat_ad_publisher_adunit_general = WECHAT_AD_PUBLISHER_ADUNIT_GENERAL()
  107. wechat_ad_publisher_adunit_general.ad_unit_id = data['ad_unit_id']
  108. wechat_ad_publisher_adunit_general.ad_unit_name = data['ad_unit_name']
  109. wechat_ad_publisher_adunit_general.ad_slot = stat_item['ad_slot']
  110. wechat_ad_publisher_adunit_general.click_count = stat_item['click_count']
  111. wechat_ad_publisher_adunit_general.click_rate = stat_item['click_rate']
  112. wechat_ad_publisher_adunit_general.date = stat_item['date']
  113. wechat_ad_publisher_adunit_general.ecpm = stat_item['ecpm']
  114. wechat_ad_publisher_adunit_general.exposure_count = stat_item['exposure_count']
  115. wechat_ad_publisher_adunit_general.exposure_rate = stat_item['exposure_rate']
  116. wechat_ad_publisher_adunit_general.income = stat_item['income']
  117. wechat_ad_publisher_adunit_general.req_succ_count = stat_item['req_succ_count']
  118. wechat_ad_publisher_adunit_general.slot_str = stat_item['slot_str']
  119. wechat_ad_publisher_adunit_general.date_str = stat_item['date'].replace('-','')
  120. wechat_ad_publisher_adunit_general.app_type = app_type
  121. session.add(wechat_ad_publisher_adunit_general)
  122. print('OK')
  123. #print('app_type = '+app_type+' ad OK')
  124. except Exception as e:
  125. traceback.print_exc()
  126. print(traceback.format_exc())
  127. #print("app_type = "+app_type+" ad trace = "traceback.format_exc())
  128. def add_ad_adpos_data(stat_item, app_type):
  129. # Use a breakpoint in the code line below to debug your script.
  130. print(f'Hi, {stat_item}') # Press ⌘F8 to toggle the breakpoint.
  131. try:
  132. with session_maker() as session:
  133. wechat_ad_publisher_adpos_general = WECHAT_AD_PUBLISHER_ADPOS_GENERAL()
  134. wechat_ad_publisher_adpos_general.ad_slot = stat_item['ad_slot']
  135. wechat_ad_publisher_adpos_general.click_count = stat_item['click_count']
  136. wechat_ad_publisher_adpos_general.click_rate = stat_item['click_rate']
  137. wechat_ad_publisher_adpos_general.date = stat_item['date']
  138. wechat_ad_publisher_adpos_general.ecpm = stat_item['ecpm']
  139. wechat_ad_publisher_adpos_general.exposure_count = stat_item['exposure_count']
  140. wechat_ad_publisher_adpos_general.exposure_rate = stat_item['exposure_rate']
  141. wechat_ad_publisher_adpos_general.income = stat_item['income']
  142. wechat_ad_publisher_adpos_general.req_succ_count = stat_item['req_succ_count']
  143. wechat_ad_publisher_adpos_general.slot_str = stat_item['slot_str']
  144. wechat_ad_publisher_adpos_general.date_str = stat_item['date'].replace('-','')
  145. wechat_ad_publisher_adpos_general.app_type = app_type
  146. session.add(wechat_ad_publisher_adpos_general)
  147. print('OK')
  148. #print('app_type = '+app_type+' ad solt OK')
  149. except Exception as e:
  150. traceback.print_exc()
  151. print(traceback.format_exc())
  152. #print("app_type = "+app_type+" solt trace"+traceback.format_exc())
  153. def post_inform(url, content_text):
  154. url = url
  155. data = json.dumps(content_text)
  156. data = bytes(data, 'utf8')
  157. print(data)
  158. #print("app_type = "+app_type+" post data = "+data)
  159. headers = {"Content-Type": 'application/json'}
  160. req = urllib.request.Request(url=url, headers=headers, data=data)
  161. try:
  162. resp = urllib.request.urlopen(req).read()
  163. print(resp.decode('utf-8'))
  164. #print("app_type = "+app_type+" post resp = "+resp.decode('utf-8'))
  165. return resp.decode('utf-8')
  166. except Exception as e:
  167. print(e)
  168. #print("app_type = "+app_type+"post e = "+e)
  169. def get_inform(url):
  170. url = url
  171. headers = {"Content-Type": 'application/json'}
  172. req = urllib.request.Request(url=url, headers=headers)
  173. try:
  174. resp = urllib.request.urlopen(req).read()
  175. print(resp.decode('utf-8'))
  176. #print("app_type = "+app_type+" get resp = "+resp.decode('utf-8'))
  177. return resp.decode('utf-8')
  178. except Exception as e:
  179. print(e)
  180. #print("app_type = "+app_type+"get e = "+e)
  181. def get_mp_info(app_type):
  182. datestr = datetime.datetime.strftime(datetime.datetime.now() - datetime.timedelta(days=+1), '%Y-%m-%d')
  183. print(datestr)
  184. #print("app_type = "+ app_type +" date = " + datestr)
  185. time_str = time.strftime("%Y:%m:%d %H")
  186. print(time_str)
  187. #print("app_type="+app_type+" time = "+time_str)
  188. md5 = hashlib.md5('{}'.format(time_str).encode(encoding='UTF-8')).hexdigest()
  189. print(md5)
  190. #print("app_type ="+app_type+"md5 = "+md5)
  191. getliveaccesstoken_url = "https://longvideoapi.piaoquantv.com/longvideoapi/weixin/getWxAccessToken/{}".format(app_type)
  192. ret = get_inform(getliveaccesstoken_url)
  193. data = json.loads(ret).get('data',{})
  194. print(data)
  195. #print("app_type = "+app_type+" getWxAccessToken date = "+data)
  196. with session_maker() as session:
  197. task = session.query(WECHAT_AD_PUBLISHER_ADUNIT_GENERAL).filter_by(date=datestr,app_type=app_type).first()
  198. if task is None:
  199. 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(
  200. data, datestr, datestr)
  201. print(getweanalysisappiddailyvisittrend_url)
  202. #print("app_type = "+app_type+" publisher/stat adunit = "+getweanalysisappiddailyvisittrend_url)
  203. ret = get_inform(getweanalysisappiddailyvisittrend_url)
  204. list = json.loads(ret).get('list',[])
  205. for item in list:
  206. add_ad_data(item, app_type)
  207. task = session.query(WECHAT_AD_PUBLISHER_ADPOS_GENERAL).filter_by(date=datestr, app_type=app_type).first()
  208. if task is None:
  209. 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(
  210. data, datestr, datestr)
  211. print(getweanalysisappiddailyvisittrend_url)
  212. #print("app_type = "+app_type +" publisher/stat adops = "+getweanalysisappiddailyvisittrend_url)
  213. ret = get_inform(getweanalysisappiddailyvisittrend_url)
  214. list = json.loads(ret).get('list',[])
  215. for item in list:
  216. add_ad_adpos_data(item, app_type)
  217. summary = json.loads(ret)['summary']
  218. summary['ad_slot'] = 'SLOT_ID_WEAPP_ALL'
  219. summary['date'] = datestr
  220. summary['slot_str'] = 'summary'
  221. add_ad_adpos_data(summary, app_type)
  222. # Press the green button in the gutter to run the script.
  223. if __name__ == '__main__':
  224. get_mp_info(0)
  225. get_mp_info(3)
  226. get_mp_info(5)
  227. get_mp_info(4)
  228. get_mp_info(6)
  229. get_mp_info(19)
  230. get_mp_info(18)
  231. get_mp_info(21)
  232. get_mp_info(22)
  233. get_mp_info(17)
  234. get_mp_info(2)
  235. get_mp_info(23)
  236. get_mp_info(24)
  237. get_mp_info(25)
  238. #get_mp_info(11)
  239. #get_mp_info(26)
  240. # See PyCharm help at https://www.jetbrains.com/help/pycharm/