test_FlowByHour_All.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. # -*- codeing = utf-8 -*-
  2. # @Time : 2022/7/13 9:51
  3. # @Author : Clown
  4. # @File : test_FlowByHour_All.py
  5. # @Software : PyCharm
  6. # -*- codeing = utf-8 -*-
  7. # @Time : 2022/7/5 17:45
  8. # @Author : Clown
  9. # @File : test_FlowByHour_M.py
  10. # @Software : PyCharm
  11. import pymysql
  12. import json
  13. import requests
  14. import csv
  15. import os
  16. import time
  17. from datetime import datetime,timedelta
  18. import sys
  19. import traceback
  20. from all_key_table import update_key_value_pair
  21. import schedule
  22. def linkTomySql(host,passwd,db_name):
  23. '''连接至数据库返回【db】,v2新增local_infile=1 打开文件导入权限'''
  24. try:
  25. #本地连接为:localhost 服务器连接为:124.222.188.59
  26. db = pymysql.connect(
  27. host=host, user="root",
  28. passwd=passwd,
  29. db=db_name,
  30. charset='utf8mb4',
  31. local_infile=1,
  32. port=63306)
  33. print('\nconnect to mysql server 成功')
  34. print('---------------------------------------')
  35. except:
  36. print("\ncould not connect to mysql server")
  37. db = "连接失败"
  38. return db
  39. def read_key_value_pair(db,brand_name,wm_plate,owner):
  40. '''按条件读取,数据库中all_key_table表里的key_value_pair字段中的值,以键值对的形式输出
  41. db:数据库,
  42. brand_name:品牌名,
  43. wm_plate:外卖平台MEITUAN或ELEME,
  44. owner:账号权限all或one
  45. '''
  46. cursor = db.cursor()
  47. sql = f'SELECT key_value_pair FROM all_key_table WHERE brand_name = "{brand_name}" AND wm_plate = "{wm_plate}" AND owner = "{owner}";'
  48. cursor.execute(sql)
  49. pair = json.loads(cursor.fetchall()[0][0])
  50. return pair
  51. def loadDataInfile(file_path ,csv_name,db,table_name):
  52. '''v2新增 执行csv文件导入数据库,注意ENCLOSED BY '"' 防止误判'''
  53. cursor = db.cursor()
  54. sql0 = f"SET global local_infile = 1;"
  55. cursor.execute(sql0)
  56. db.commit()
  57. sql1 = f'''LOAD DATA LOCAL INFILE '{file_path+'/'+csv_name}' REPLACE INTO TABLE {table_name} FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES ;'''
  58. cursor.execute(sql1)
  59. db.commit()
  60. sql2= f"SET global local_infile = 0;"
  61. cursor.execute(sql2)
  62. db.commit()
  63. cursor.close()
  64. def update_scriptrunninglogs(log_date,log_time,running_Time,operation_results,table_name,db):
  65. '''将脚本执行情况发送至【脚本执行日志】表
  66. 配套内容
  67. from datetime import datetime
  68. import sys
  69. import traceback
  70. time_begin = time.time()
  71. log_date = datetime.now().strftime("%Y-%m-%d") # 日志记录日期
  72. log_time = datetime.now().strftime('%H:%M:%S') # 日志记录时间
  73. df_name = '数据库表名'
  74. try:
  75. operation_results = '执行成功'
  76. except Exception as e:
  77. operation_results = traceback.format_exc()
  78. running_Time = time.time() - time_begin # 脚本运行时长
  79. '''
  80. try:
  81. sql = "INSERT INTO scriptrunninglogs_test VALUES (%s,%s,%s,%s,%s,%s,%s)"#date, time, running_Time, script_name, operation_results, table_name, id
  82. script_name = os.path.basename(sys.argv[0])
  83. value = (log_date,log_time,running_Time,script_name,operation_results,table_name,0)
  84. cursor = db.cursor()
  85. cursor.execute(sql, value) # 执行sql语句
  86. db.commit()
  87. cursor.close()
  88. except:
  89. result = "数据库连接失败"
  90. print(result)
  91. def reset_mysql_table(db,table_name):
  92. cursor = db.cursor()
  93. sql = f'DELETE FROM {table_name} WHERE log_date = CURRENT_DATE() '
  94. cursor.execute(sql)
  95. db.commit()
  96. print(f'【{table_name}】当日数据重置成功,可导入新数据')
  97. def get_shops_info_to_list(db,brand_name,wm_plate,key_name):
  98. '''获取门店信息表【shops_info_to_list】中的信息,
  99. 并返回表单shops_info_df【shop_id,shop_name,update_datetime,info_for_script】
  100. db:数据库信息
  101. brand_name:品牌
  102. wm_plate:外卖平台
  103. key_name:关键信息字段名,如无填‘’,如有填对应键值对的key
  104. '''
  105. cursor = db.cursor()
  106. if key_name == '':
  107. sql = f'SELECT shop_id,shop_name,update_datetime FROM shops_info_for_script WHERE brand_name = "{brand_name}" AND wm_plate = "{wm_plate}";'
  108. cursor.execute(sql)
  109. shops_info = cursor.fetchall()
  110. shops_info_df = []
  111. for shop_info in shops_info:
  112. shop_info_dict = {'shop_id':shop_info[0],
  113. 'shop_name':shop_info[1],
  114. 'update_datetime':shop_info[2],
  115. 'info_for_script':''}
  116. shops_info_df.append(shop_info_dict)
  117. return shops_info_df
  118. else:
  119. sql = f'SELECT shop_id,shop_name,update_datetime,info_for_script -> "$.{key_name}" FROM shops_info_for_script WHERE brand_name = "{brand_name}" AND wm_plate = "{wm_plate}";'
  120. cursor.execute(sql)
  121. shops_info = cursor.fetchall()
  122. shops_info_df = []
  123. for shop_info in shops_info:
  124. shop_info_dict = {'shop_id':shop_info[0],
  125. 'shop_name':shop_info[1],
  126. 'update_datetime':shop_info[2],
  127. f'{key_name}':shop_info[3]}
  128. shops_info_df.append(shop_info_dict)
  129. return shops_info_df
  130. def test_FlowByHour_M(file_path,brand_name,mt_pair,shops_info_df):
  131. '''
  132. return: error or (csv_name_storage, csv_name_application)
  133. v2优化:增加批量错误判断,方便终止此函数
  134. '''
  135. #创建储存表
  136. csv_name_storage = 'test_FlowByHour_M_storage.csv'
  137. title_storage = ['script_name', 'brand_name', 'shop_id', 'wm_plate', 'date', 'time', 'data_details', 'id']
  138. f_storage = open(file_path+'/'+csv_name_storage, mode='w', encoding='utf-8-sig',newline="")
  139. writer_storage = csv.writer(f_storage)
  140. writer_storage.writerow(title_storage)
  141. #创建生产表
  142. csv_name_application = 'test_FlowByHour_M_application.csv'
  143. title_application = ['id', 'log_date', 'date_of_data', 'brand_name', 'shop_id', 'shop_name', 'timeSign',
  144. 'today_exp_pv', 'today_exp_uv', 'today_clk_pv', 'today_clk_uv', 'today_valid_order_cnt', 'today_valid_order_user_cnt', 'today_clk_exp_rate', 'today_ord_clk_rate',
  145. 'last_day_exp_pv', 'last_day_exp_uv', 'last_day_clk_pv', 'last_day_clk_uv', 'last_day_valid_order_cnt', 'last_day_valid_order_user_cnt', 'last_day_clk_exp_rate', 'last_day_ord_clk_rate',
  146. 'totalExposureAmount', 'uvCount', 'totalCost', 'averageCost']
  147. #['id', '记录日期', '数据所在日期', '门店id', '店名', '时段', '曝光次数', '点击率%', '点击次数', '单次点击花费', '时段竞价花费']
  148. f_application = open(file_path + '/' + csv_name_application, mode='w', encoding='utf-8-sig', newline="")
  149. writer_application = csv.writer(f_application)
  150. writer_application.writerow(title_application)
  151. #通用参数
  152. script_name = 'test_FlowByHour_M'
  153. wm_plate = 'MEITUAN'
  154. date = datetime.now().strftime('%Y-%m-%d')
  155. time = datetime.now().strftime('%H:%M:%S')
  156. beginTime = (datetime.today()).strftime('%Y-%m-%d') #2022-06-23
  157. endTime = (datetime.today() + timedelta(days=-1)).strftime('%Y-%m-%d') #2022-06-23
  158. timeSign = datetime.now().strftime('%H:%M') #20220706优化
  159. # shops_cnt = len(shops_info_df) # v2优化
  160. shops_cnt = 1
  161. check_error_cnt = 0 # v2优化
  162. acctId = mt_pair['data']['session']['acctId']
  163. token = mt_pair['data']['session']['token']
  164. #门店信息
  165. # for shop_info in shops_info_df:
  166. # shop_id = shop_info['shop_id']
  167. # shop_name = shop_info['shop_name']
  168. # info_update_datetime = shop_info['update_datetime']
  169. shop_id = 8038750
  170. shop_name = '浆小白·粉面粥·豆浆夜市(周浦万达店)'
  171. info_update_datetime = datetime.today()
  172. #联网获取信息
  173. url_flow = f'https://waimaieapp.meituan.com/bizdata/flow/single/pc/overview?acctId={acctId}&wmPoiId={shop_id}&durationType=5&tabType=3&circleType=1'
  174. cookie = f'acctId={acctId}; ' \
  175. f'token={token}; ' \
  176. f'wmPoiId={shop_id}; '
  177. headers_flow = {
  178. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36',
  179. 'cookie': cookie}
  180. url_wager = f'https://waimaieapp.meituan.com/ad/v3/statistics/cpc/today/info?acctId={acctId}&wmPoiId={shop_id}&token={token}&platform=0&bizad_cityId=310100&bizad_second_city_id=310100&bizad_third_city_id=310115'
  181. headers_wager = {
  182. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36'}
  183. if int(info_update_datetime.strftime("%Y%m%d")) >= int(datetime.strptime(beginTime,"%Y-%m-%d").strftime("%Y%m%d")):
  184. try:
  185. data_details_flow = requests.get(url_flow, headers= headers_flow).json()
  186. data_details_wager = requests.get(url_wager, headers= headers_wager).json()
  187. data_details = {"data_flow":data_details_flow,
  188. "data_wager":data_details_wager}
  189. #储存信息至csv存储表
  190. row_storage = [script_name, brand_name, shop_id, wm_plate, date, time, json.dumps(data_details, ensure_ascii= False), 0]
  191. #解析数据存储至csv生产表
  192. try:
  193. data_all_flow = data_details_flow['data']
  194. today_exp_pv = data_all_flow['exposureCnt']['base'] #曝光次数
  195. today_exp_uv = data_all_flow['exposureNum']['base'] #曝光人数
  196. today_clk_pv = data_all_flow['visitCnt']['base'] #进店次数
  197. today_clk_uv = data_all_flow['visitNum']['base'] #进店人数
  198. today_valid_order_cnt = data_all_flow['orderCnt']['base'] #下单次数
  199. today_valid_order_user_cnt = data_all_flow['orderNum']['base'] #下单人数
  200. today_clk_exp_rate = data_all_flow['visitRate']['base'] #进店转化率
  201. today_ord_clk_rate = data_all_flow['orderRate']['base'] #下单转化率
  202. last_day_exp_pv = today_exp_pv - data_all_flow['exposureCnt']['baseDelta'] # 曝光次数
  203. last_day_exp_uv = today_exp_uv - data_all_flow['exposureNum']['baseDelta'] # 曝光人数
  204. last_day_clk_pv = today_clk_pv - data_all_flow['visitCnt']['baseDelta'] # 进店次数
  205. last_day_clk_uv = today_clk_uv - data_all_flow['visitNum']['baseDelta'] # 进店人数
  206. last_day_valid_order_cnt = today_valid_order_cnt - data_all_flow['orderCnt']['baseDelta'] # 下单次数
  207. last_day_valid_order_user_cnt = today_valid_order_user_cnt - data_all_flow['orderNum']['baseDelta'] # 下单人数
  208. last_day_clk_exp_rate = today_clk_exp_rate - data_all_flow['visitRate']['baseDelta'] # 进店转化率
  209. last_day_ord_clk_rate = today_ord_clk_rate - data_all_flow['orderRate']['baseDelta'] # 下单转化率
  210. data_all_wager = data_details_wager['data']
  211. totalExposureAmount = data_all_wager['showCount'] #累计曝光次数
  212. uvCount = data_all_wager['clickCount'] #竞价进店次数
  213. totalCost = data_all_wager['cost'] #累计竞价花费
  214. averageCost = data_all_wager['avgPrice'] #单次点击花费
  215. # 解析数据存储至csv生产表
  216. row_application = [0,date, beginTime, brand_name, shop_id, shop_name, timeSign,
  217. today_exp_pv, today_exp_uv, today_clk_pv, today_clk_uv, today_valid_order_cnt, today_valid_order_user_cnt, today_clk_exp_rate, today_ord_clk_rate,
  218. last_day_exp_pv, last_day_exp_uv, last_day_clk_pv, last_day_clk_uv, last_day_valid_order_cnt, last_day_valid_order_user_cnt, last_day_clk_exp_rate, last_day_ord_clk_rate,
  219. totalExposureAmount, uvCount, totalCost, averageCost]
  220. writer_application.writerow(row_application)
  221. except:
  222. # 解析数据存储至csv生产表
  223. row_application = [0, date, beginTime, brand_name, shop_id, shop_name, timeSign, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #20220706优化
  224. writer_application.writerow(row_application)
  225. except:
  226. check_error_cnt += 1 # v2优化
  227. data_details = {'result': '此门店未打开营业or账户号已无效or相关界面无参数,请核实!'}
  228. # 储存信息至csv存储表
  229. row_storage = [script_name, brand_name, shop_id, wm_plate, date, time, json.dumps(data_details, ensure_ascii=False), 0]
  230. # 解析数据存储至csv生产表
  231. row_application = [0, date, beginTime, brand_name, shop_id, shop_name, timeSign, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #20220706优化
  232. writer_application.writerow(row_application)
  233. else:
  234. check_error_cnt += 1 # v2优化
  235. data_details = {'result':'此门店未打开营业or账户号已无效or相关界面无参数,请核实!'}
  236. # 储存信息至csv存储表
  237. row_storage = [script_name, brand_name, shop_id, wm_plate, date, time,json.dumps(data_details, ensure_ascii=False), 0]
  238. # 解析数据存储至csv生产表
  239. row_application = [0, date, beginTime, brand_name, shop_id, shop_name, timeSign, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #20220706优化
  240. writer_application.writerow(row_application)
  241. writer_storage.writerow(row_storage)
  242. if shops_cnt == check_error_cnt:#v2优化
  243. e = 0/0 #v2优化
  244. else: #v2优化
  245. print(f'{brand_name}\n【{csv_name_storage}】\n【{csv_name_application}】\n加载成功!\n')
  246. return csv_name_storage,csv_name_application
  247. def running_m():
  248. # 日志参数
  249. time_begin = time.time()
  250. log_date = datetime.now().strftime("%Y-%m-%d") # 日志记录日期
  251. log_time = datetime.now().strftime('%H:%M:%S') # 日志记录时间
  252. # 通用参数
  253. host = 'localhost'
  254. passwd = '111???clown'
  255. db_name = 'hexingxing'
  256. # brand_names = ['粥小鲜','浆小白']
  257. wm_plate = 'MEITUAN'
  258. owner = 'all'
  259. key_name = ''
  260. file_path = 'C:/Users/ClownHe/Desktop/goods'
  261. table_name = '[test_flowbyhour_m] Storage And App'
  262. table_name_storage = 'data_storage_test_flowbyhour_m'
  263. table_name_app = 'data_app_test_flowbyhour_m'
  264. operation_results = '执行成功'
  265. brand_name = '浆小白'
  266. # 脚本执行
  267. db = linkTomySql(host, passwd, db_name)
  268. # for brand_name in brand_names:
  269. mt_pair = read_key_value_pair(db, brand_name, wm_plate, owner)
  270. # shops_info_df = get_shops_info_to_list(db,brand_name,wm_plate,key_name)
  271. shops_info_df = 0
  272. try:
  273. try:
  274. csv_name_storage, csv_name_application = test_FlowByHour_M(file_path, brand_name, mt_pair,
  275. shops_info_df)
  276. except Exception as x:
  277. print('重载关键表',x)
  278. update_key_value_pair(db, brand_name, wm_plate, owner, '') # 报错更新【all_key_table】
  279. csv_name_storage, csv_name_application = test_FlowByHour_M(file_path, brand_name, mt_pair,
  280. shops_info_df)
  281. operation_results = operation_results + f',更新【{brand_name}】【{wm_plate}】【all_key_table】'
  282. loadDataInfile(file_path, csv_name_storage, db, table_name_storage)
  283. print(f'【{csv_name_storage}】导入成功')
  284. loadDataInfile(file_path, csv_name_application, db, table_name_app)
  285. print(f'【{csv_name_application}】导入成功')
  286. print(f'本次脚本执行总用时{(time.time() - time_begin) / 60} min')
  287. except Exception as e:
  288. operation_results = traceback.format_exc()
  289. running_Time = time.time() - time_begin # 脚本运行时长
  290. db = linkTomySql(host, passwd, db_name)
  291. update_scriptrunninglogs(log_date, log_time, running_Time, operation_results, table_name, db)
  292. print('Working done!')
  293. time_kill = time.time() - time_begin
  294. return time_kill
  295. def test_FlowByHour_E(file_path,brand_name,elm_pair,shops_info_df):
  296. '''
  297. return: error or (csv_name_storage, csv_name_application)
  298. v2优化:增加批量错误判断,方便终止此函数
  299. '''
  300. #创建储存表
  301. csv_name_storage = 'test_FlowByHour_E_storage.csv'
  302. title_storage = ['script_name', 'brand_name', 'shop_id', 'wm_plate', 'date', 'time', 'data_details', 'id']
  303. f_storage = open(file_path+'/'+csv_name_storage, mode='w', encoding='utf-8-sig',newline="")
  304. writer_storage = csv.writer(f_storage)
  305. writer_storage.writerow(title_storage)
  306. #创建生产表
  307. csv_name_application = 'test_FlowByHour_E_application.csv'
  308. title_application = ['id', 'log_date', 'date_of_data', 'brand_name', 'shop_id', 'shop_name', 'timeSign',
  309. 'today_exp_pv', 'today_exp_uv', 'today_clk_pv', 'today_clk_uv', 'today_valid_order_cnt', 'today_valid_order_user_cnt', 'today_clk_exp_rate', 'today_ord_clk_rate',
  310. 'last_day_exp_pv', 'last_day_exp_uv', 'last_day_clk_pv', 'last_day_clk_uv', 'last_day_valid_order_cnt', 'last_day_valid_order_user_cnt', 'last_day_clk_exp_rate', 'last_day_ord_clk_rate',
  311. 'totalExposureAmount', 'uvCount', 'totalCost', 'averageCost']
  312. #['id', '记录日期', '数据所在日期', '门店id', '店名', '时段', '曝光次数', '点击率%', '点击次数', '单次点击花费', '时段竞价花费']
  313. f_application = open(file_path + '/' + csv_name_application, mode='w', encoding='utf-8-sig', newline="")
  314. writer_application = csv.writer(f_application)
  315. writer_application.writerow(title_application)
  316. #通用参数
  317. script_name = 'test_FlowByHour_E'
  318. wm_plate = 'ELEME'
  319. date = datetime.now().strftime('%Y-%m-%d')
  320. time = datetime.now().strftime('%H:%M:%S')
  321. beginTime = (datetime.today()).strftime('%Y-%m-%d') #2022-06-23
  322. endTime = (datetime.today() + timedelta(days=-1)).strftime('%Y-%m-%d') #2022-06-23
  323. timeSign = datetime.now().strftime('%H:%M') #20220706优化
  324. # shops_cnt = len(shops_info_df) # v2优化
  325. shops_cnt = 1
  326. check_error_cnt = 0 # v2优化
  327. ksid = elm_pair['data']['session']['ksid']
  328. url_flow = 'https://httpizza.ele.me/napos-miracle-stats/SingleFlowService.realtimeFlowSummary'
  329. url_wager = 'https://app-api.shop.ele.me/alchemy/invoke/?method=wager.getUVSummary'
  330. headers = {
  331. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36',
  332. 'content-type': 'application/json'}
  333. #门店信息
  334. # for shop_info in shops_info_df:
  335. # shop_id = shop_info['shop_id']
  336. # shop_name = shop_info['shop_name']
  337. # info_update_datetime = shop_info['update_datetime']
  338. shop_id = 173858169
  339. shop_name = '浆小白·粉面粥·豆浆夜市(周浦万达店)'
  340. info_update_datetime = datetime.today()
  341. #联网获取信息
  342. json_params_flow = {"ksid":ksid,"requestParam":{"shopId":shop_id,"contrastType":"yesterday"}}
  343. json_params_wager = {"id":"3FC49D97DC28490990FC243CE038B9CA|1657016560816",
  344. "metas":{"appName":"bs-river-bid",
  345. "appVersion":"4.4.0",
  346. "ksid":ksid},
  347. "service":"wager",
  348. "method":"getUVSummary",
  349. "params":{"restaurantId":shop_id,
  350. "type":None,
  351. "beginTime":f"{datetime.today().strftime('%Y-%m-%d')}",
  352. "endTime":f"{datetime.today().strftime('%Y-%m-%d')}"},
  353. "ncp":"2.0.0"}
  354. if int(info_update_datetime.strftime("%Y%m%d")) >= int(datetime.strptime(beginTime,"%Y-%m-%d").strftime("%Y%m%d")):
  355. try:
  356. data_details_flow = requests.post(url_flow, json= json_params_flow, headers= headers).json()
  357. data_details_wager = requests.post(url_wager, json= json_params_wager, headers= headers).json()
  358. data_details = {"data_flow":data_details_flow,
  359. "data_wager":data_details_wager}
  360. #储存信息至csv存储表
  361. row_storage = [script_name, brand_name, shop_id, wm_plate, date, time, json.dumps(data_details, ensure_ascii= False), 0]
  362. #解析数据存储至csv生产表
  363. try:
  364. data_all_flow = data_details_flow['data']['result'][0]
  365. today_exp_pv = data_all_flow['today_exp_pv'] #曝光次数
  366. today_exp_uv = data_all_flow['today_exp_uv'] #曝光人数
  367. today_clk_pv = data_all_flow['today_clk_pv'] #进店次数
  368. today_clk_uv = data_all_flow['today_clk_uv'] #进店人数
  369. today_valid_order_cnt = data_all_flow['today_valid_order_cnt'] #下单次数
  370. today_valid_order_user_cnt = data_all_flow['today_valid_order_user_cnt'] #下单人数
  371. today_clk_exp_rate = data_all_flow['today_clk_exp_rate'] #进店转化率
  372. today_ord_clk_rate = data_all_flow['today_ord_clk_rate'] #下单转化率
  373. last_day_exp_pv = data_all_flow['last_day_exp_pv'] # 曝光次数
  374. last_day_exp_uv = data_all_flow['last_day_exp_uv'] # 曝光人数
  375. last_day_clk_pv = data_all_flow['last_day_clk_pv'] # 进店次数
  376. last_day_clk_uv = data_all_flow['last_day_clk_uv'] # 进店人数
  377. last_day_valid_order_cnt = data_all_flow['last_day_valid_order_cnt'] # 下单次数
  378. last_day_valid_order_user_cnt = data_all_flow['last_day_valid_order_user_cnt'] # 下单人数
  379. last_day_clk_exp_rate = data_all_flow['last_day_clk_exp_rate'] # 进店转化率
  380. last_day_ord_clk_rate = data_all_flow['last_day_ord_clk_rate'] # 下单转化率
  381. data_all_wager = data_details_wager['result']
  382. totalExposureAmount = data_all_wager['totalExposureAmount'] #累计曝光次数
  383. uvCount = data_all_wager['uvCount'] #竞价进店次数
  384. totalCost = data_all_wager['totalCost'] #累计竞价花费
  385. averageCost = data_all_wager['averageCost'] #单次点击花费
  386. # 解析数据存储至csv生产表
  387. row_application = [0,date, beginTime, brand_name, shop_id, shop_name, timeSign,
  388. today_exp_pv, today_exp_uv, today_clk_pv, today_clk_uv, today_valid_order_cnt, today_valid_order_user_cnt, today_clk_exp_rate, today_ord_clk_rate,
  389. last_day_exp_pv, last_day_exp_uv, last_day_clk_pv, last_day_clk_uv, last_day_valid_order_cnt, last_day_valid_order_user_cnt, last_day_clk_exp_rate, last_day_ord_clk_rate,
  390. totalExposureAmount, uvCount, totalCost, averageCost]
  391. writer_application.writerow(row_application)
  392. except:
  393. # 解析数据存储至csv生产表
  394. row_application = [0, date, beginTime, brand_name, shop_id, shop_name, timeSign, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #20220706优化
  395. writer_application.writerow(row_application)
  396. except:
  397. check_error_cnt += 1 # v2优化
  398. data_details = {'result': '此门店未打开营业or账户号已无效or相关界面无参数,请核实!'}
  399. # 储存信息至csv存储表
  400. row_storage = [script_name, brand_name, shop_id, wm_plate, date, time, json.dumps(data_details, ensure_ascii=False), 0]
  401. # 解析数据存储至csv生产表
  402. row_application = [0, date, beginTime, brand_name, shop_id, shop_name, timeSign, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #20220706优化
  403. writer_application.writerow(row_application)
  404. else:
  405. check_error_cnt += 1 # v2优化
  406. data_details = {'result':'此门店未打开营业or账户号已无效or相关界面无参数,请核实!'}
  407. # 储存信息至csv存储表
  408. row_storage = [script_name, brand_name, shop_id, wm_plate, date, time,json.dumps(data_details, ensure_ascii=False), 0]
  409. # 解析数据存储至csv生产表
  410. row_application = [0, date, beginTime, brand_name, shop_id, shop_name, timeSign, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #20220706优化
  411. writer_application.writerow(row_application)
  412. writer_storage.writerow(row_storage)
  413. if shops_cnt == check_error_cnt:#v2优化
  414. e = 0/0 #v2优化
  415. else: #v2优化
  416. print(f'{brand_name}\n【{csv_name_storage}】\n【{csv_name_application}】\n加载成功!\n')
  417. return csv_name_storage,csv_name_application
  418. def running_e():
  419. # 日志参数
  420. time_begin = time.time()
  421. log_date = datetime.now().strftime("%Y-%m-%d") # 日志记录日期
  422. log_time = datetime.now().strftime('%H:%M:%S') # 日志记录时间
  423. # 通用参数
  424. host = 'localhost'
  425. passwd = '111???clown'
  426. db_name = 'hexingxing'
  427. # brand_names = ['粥小鲜','浆小白']
  428. wm_plate = 'ELEME'
  429. owner = 'all'
  430. key_name = ''
  431. file_path = 'C:/Users/ClownHe/Desktop/goods'
  432. table_name = '[test_flowbyhour_e] Storage And App'
  433. table_name_storage = 'data_storage_test_flowbyhour_e'
  434. table_name_app = 'data_app_test_flowbyhour_e'
  435. operation_results = '执行成功'
  436. brand_name = '浆小白'
  437. # 脚本执行
  438. db = linkTomySql(host, passwd, db_name)
  439. # for brand_name in brand_names:
  440. elm_pair = read_key_value_pair(db, brand_name, wm_plate, owner)
  441. # shops_info_df = get_shops_info_to_list(db,brand_name,wm_plate,key_name)
  442. shops_info_df = 0
  443. try:
  444. try:
  445. csv_name_storage, csv_name_application = test_FlowByHour_E(file_path, brand_name, elm_pair,
  446. shops_info_df)
  447. except Exception as x:
  448. print('重载关键表',x)
  449. update_key_value_pair(db, brand_name, wm_plate, owner, '') # 报错更新【all_key_table】
  450. csv_name_storage, csv_name_application = test_FlowByHour_E(file_path, brand_name, elm_pair,
  451. shops_info_df)
  452. operation_results = operation_results + f',更新【{brand_name}】【{wm_plate}】【all_key_table】'
  453. loadDataInfile(file_path, csv_name_storage, db, table_name_storage)
  454. print(f'【{csv_name_storage}】导入成功')
  455. loadDataInfile(file_path, csv_name_application, db, table_name_app)
  456. print(f'【{csv_name_application}】导入成功')
  457. print(f'本次脚本执行总用时{(time.time() - time_begin) / 60} min')
  458. except Exception as e:
  459. operation_results = traceback.format_exc()
  460. running_Time = time.time() - time_begin # 脚本运行时长
  461. db = linkTomySql(host, passwd, db_name)
  462. update_scriptrunninglogs(log_date, log_time, running_Time, operation_results, table_name, db)
  463. print('Working done!')
  464. time_kill = time.time() - time_begin
  465. return time_kill
  466. if __name__ == '__main__':
  467. # schedule.every().hour.at("00:10").do(running) # 每个小时的n分n秒执行一次
  468. # schedule.every().hour.at("05:10").do(running) # 每个小时的n分n秒执行一次
  469. # schedule.every().hour.at("10:10").do(running) # 每个小时的n分n秒执行一次
  470. # schedule.every().hour.at("15:10").do(running) # 每个小时的n分n秒执行一次
  471. # schedule.every().hour.at("20:10").do(running) # 每个小时的n分n秒执行一次
  472. # schedule.every().hour.at("25:10").do(running) # 每个小时的n分n秒执行一次
  473. # schedule.every().hour.at("30:10").do(running) # 每个小时的n分n秒执行一次
  474. # schedule.every().hour.at("35:10").do(running) # 每个小时的n分n秒执行一次
  475. # schedule.every().hour.at("40:10").do(running) # 每个小时的n分n秒执行一次
  476. # schedule.every().hour.at("45:10").do(running) # 每个小时的n分n秒执行一次
  477. # schedule.every().hour.at("50:10").do(running) # 每个小时的n分n秒执行一次
  478. # schedule.every().hour.at("57:10").do(running) # 每个小时的n分n秒执行一次
  479. # schedule.every().minute.at(":05").do(running) # 每个小时的n分n秒执行一次
  480. # schedule.every().minute.at(":15").do(running) # 每个小时的n分n秒执行一次
  481. # schedule.every().minute.at(":25").do(running) # 每个小时的n分n秒执行一次
  482. # schedule.every().minute.at(":35").do(running) # 每个小时的n分n秒执行一次
  483. # schedule.every().minute.at(":45").do(running) # 每个小时的n分n秒执行一次
  484. schedule.every().minute.at(":10").do(running_m) # 每个小时的n分n秒执行一次
  485. schedule.every().minute.at(":15").do(running_e)
  486. while True:
  487. schedule.run_pending() # 运行所有可运行的任务