data_nwp_ftp.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # @FileName :data_nwp_ftp.py
  4. # @Time :2024/12/26 08:38
  5. # @Author :David
  6. # @Company: shenyang JY
  7. import requests, json
  8. from datetime import timedelta
  9. from ftplib import FTP
  10. import threading, glob, pytz
  11. import pandas as pd
  12. from pytz import timezone
  13. from flask import Flask,request,jsonify
  14. import time, datetime, os, traceback, re
  15. import zipfile, tempfile, shutil, fnmatch
  16. from common.database_dml import insert_data_into_mongo
  17. from apscheduler.schedulers.background import BackgroundScheduler
  18. from apscheduler.triggers.cron import CronTrigger
  19. from common.logs import Log
  20. logger = Log('data-processing').logger
  21. app = Flask('data_nwp_ftp——service')
  22. def update_thread():
  23. thread = threading.Thread(target=start_jobs)
  24. thread.start()
  25. def start_jobs():
  26. scheduler = BackgroundScheduler()
  27. scheduler.configure({'timezone': timezone("Asia/Shanghai")})
  28. trigger1 = CronTrigger(
  29. hour='0,1,2,4,5,6,11,12,13,16,17,18', # 主触发小时
  30. minute='0-50/10', # 每 10 分钟一次,覆盖 00:00-00:50
  31. timezone='Asia/Shanghai' # 按需设置时区
  32. )
  33. scheduler.add_job(func=download_zip_files_from_ftp, trigger=trigger1)
  34. scheduler.start()
  35. def match_date(date, filename):
  36. given_date = datetime.datetime.strptime(date, '%Y%m%d')
  37. date_pattern = re.compile(r'(\d{8})')
  38. match = date_pattern.search(filename)
  39. if match:
  40. filename_str = match.group(0)
  41. filename_date = datetime.datetime.strptime(filename_str, '%Y%m%d')
  42. if filename_date <= given_date:
  43. return True
  44. def delete_zip_files(date):
  45. xxl_path = ftp_params['xxl']['local_dir']
  46. # 遍历文件夹中的所有文件
  47. for root, dirs, files in os.walk(xxl_path):
  48. for filename in files:
  49. # 检查文件名是否以 'meteo_date_' 开头且以 '.zip' 结尾
  50. if fnmatch.fnmatch(filename, f'*.zip') and match_date(date, filename):
  51. # 构建文件的完整路径
  52. file_path = os.path.join(xxl_path, filename)
  53. # 删除文件
  54. try:
  55. os.remove(file_path)
  56. print(f"Deleted file: {file_path}")
  57. except OSError as e:
  58. print(f"Error deleting file {file_path}: {e.strerror}")
  59. for farmId in dirs:
  60. target_dir_path = os.path.join(root, farmId)
  61. for file_name in os.listdir(target_dir_path):
  62. csv_file_path = os.path.join(target_dir_path, file_name)
  63. if fnmatch.fnmatch(csv_file_path, f'*.csv') and match_date(date, file_name):
  64. try:
  65. os.remove(csv_file_path)
  66. print(f"Deleted file: {csv_file_path}")
  67. except OSError as e:
  68. print(f"Error deleting file {csv_file_path}: {e.strerror}")
  69. def get_moment_next(schedule_dt=None):
  70. if schedule_dt is not None:
  71. now = datetime.datetime.strptime(str(schedule_dt), '%Y-%m-%d %H:%M:%S')
  72. else:
  73. now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai"))
  74. date = now.strftime('%Y%m%d')
  75. if now.hour == 18:
  76. moment = '18'
  77. elif now.hour > 18:
  78. moment = '00'
  79. elif now.hour == 12:
  80. moment = '12'
  81. elif now.hour > 12:
  82. moment = '18'
  83. elif now.hour == 6:
  84. moment = '06'
  85. elif now.hour > 6:
  86. moment = '12'
  87. elif 2 >= now.hour >= 0:
  88. moment = '00'
  89. else:
  90. moment = '06'
  91. return date, moment
  92. def get_previous_moment(original_date, original_moment):
  93. # 将原date和moment转换为上海时区的datetime对象
  94. tz_shanghai = timezone('Asia/Shanghai')
  95. original_dt = datetime.datetime.strptime(f"{original_date}{original_moment}", "%Y%m%d%H")
  96. original_dt = tz_shanghai.localize(original_dt)
  97. # 减去6小时
  98. new_dt = original_dt - datetime.timedelta(hours=6)
  99. # 转换为原方法可接受的schedule_dt字符串格式
  100. schedule_dt_str = new_dt.strftime('%Y-%m-%d %H:%M:%S')
  101. # 调用原方法获取新的date和moment
  102. new_date, new_moment = get_moment_next(schedule_dt=schedule_dt_str)
  103. return new_date, new_moment
  104. def download_zip_files_from_ftp(moment=None):
  105. now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai"))
  106. date = now.strftime("%Y%m%d")
  107. date_2 = (now - timedelta(days=2)).strftime("%Y%m%d")
  108. if moment is None:
  109. date, moment = get_moment_next()
  110. host = 'xxl'
  111. ftp_host, ftp_user, ftp_password, remote_dir, local_dir = ftp_params[host]['host'], ftp_params[host]['user'], ftp_params[host]['password'], ftp_params[host]['remote_dir'], ftp_params['xxl']['local_dir']
  112. zip_extension = f'meteoforce_{date}{str(moment)}_*.zip'
  113. zip_file_path = []
  114. # 连接到FTP服务器
  115. with FTP(ftp_host) as ftp:
  116. ftp.login(user=ftp_user, passwd=ftp_password)
  117. # 切换到远程目录
  118. ftp.cwd(remote_dir)
  119. # 获取远程目录中的文件和目录列表
  120. files = ftp.nlst()
  121. # 遍历文件列表,找到ZIP文件并下载
  122. for file_name in files:
  123. if fnmatch.fnmatch(file_name, zip_extension):
  124. start = time.time()
  125. remote_file_path = os.path.join(remote_dir, file_name)
  126. local_file_path = os.path.join(local_dir, file_name)
  127. if os.path.isfile(local_file_path):
  128. continue
  129. with open(local_file_path, 'wb') as local_file:
  130. logger.info(f"Downloading {remote_file_path} to {local_file_path}")
  131. ftp.retrbinary(f'RETR {remote_file_path}', local_file.write)
  132. end = time.time()
  133. now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai"))
  134. logger_text = f"下载完成时间:{now.strftime('%Y-%m-%d %H:%M:%S')},下载 {file_name} 文件,用时 {end - start}秒"
  135. logger.info(logger_text)
  136. send_message(file_name, logger_text)
  137. zip_file_path.append(local_file_path)
  138. # 解压 ZIP 文件到临时目录
  139. for zip_file_p in zip_file_path:
  140. with zipfile.ZipFile(zip_file_p, 'r') as zip_ref:
  141. zip_ref.extractall(local_dir)
  142. # 删除前天之前所有 ZIP 文件
  143. delete_zip_files(date_2)
  144. def select_file_to_mongo(args, date, moment):
  145. farmId, isDq = args['farmId'], args['isDq']
  146. csv_file_format = 'meteoforce_{}_{}_*.csv'.format(farmId, date + str(moment))
  147. csv_file_weather = csv_file_format.replace('*', 'weather')
  148. csv_file_power = csv_file_format.replace('*', 'power')
  149. csv_weather_path, csv_power_path = False, False
  150. # 查找目标目录并读取 CSV 文件
  151. for root, dirs, files in os.walk(ftp_params['xxl']['local_dir']):
  152. if farmId in dirs:
  153. target_dir_path = os.path.join(root, farmId)
  154. for file_name in os.listdir(target_dir_path):
  155. csv_file_path = os.path.join(target_dir_path, file_name)
  156. if fnmatch.fnmatch(file_name, csv_file_weather):
  157. csv_weather_path = csv_file_path
  158. logger.info("***找到nwp:{}***".format(csv_weather_path))
  159. if fnmatch.fnmatch(file_name, csv_file_power):
  160. csv_power_path = csv_file_path
  161. logger.info("***找到power:{}***".format(csv_power_path))
  162. if csv_weather_path or csv_power_path:
  163. break
  164. if csv_weather_path is False:
  165. logger.info("获取nwp文件异常:找不到场站 {} nwp文件".format(farmId))
  166. return False
  167. # 使用 pandas 读取 CSV 文件
  168. weather = pd.read_csv(csv_weather_path)
  169. power = pd.read_csv(csv_power_path) if csv_power_path else None
  170. if isDq:
  171. if csv_weather_path and csv_power_path:
  172. power.drop(columns=['farm_id'], inplace=True)
  173. weather_power = pd.merge(weather, power, on='date_time')
  174. # 截取D0-D13时段数据
  175. df = select_dx_from_nwp(weather_power, args)
  176. insert_data_into_mongo(df, args)
  177. else:
  178. df = select_dx_from_nwp(weather, args)
  179. insert_data_into_mongo(df, args)
  180. logger.info(f"CSV 文件 {csv_file_power} 在目标目录 {farmId} 中未找到")
  181. else:
  182. if csv_weather_path:
  183. weather = select_dx_from_nwp(weather, args)
  184. # 截取D0-D13时段数据
  185. df = select_dx_from_nwp(weather, args)
  186. insert_data_into_mongo(df, args)
  187. else:
  188. logger.info(f"CSV 文件 {csv_file_weather} 在目标目录 {farmId} 中未找到")
  189. return True
  190. def select_dx_from_nwp(df, args):
  191. date, moment = get_moment_next(args.get('dt'))
  192. date = datetime.datetime.strptime(date, "%Y%m%d")
  193. date_begin = date + pd.Timedelta(days=int(args.get('day_begin', 'D0')[1:]))
  194. date_end = date + pd.Timedelta(days=int(args.get('day_end', 'D13')[1:]))
  195. df['date_time'] = df['date_time'].str.replace("_", " ")
  196. df['date_time'] = pd.to_datetime(df['date_time'])
  197. df.set_index('date_time', inplace=True)
  198. df = df.loc[date_begin.strftime('%Y-%m-%d'): date_end.strftime('%Y-%m-%d')].reset_index(drop=False)
  199. df.reset_index(drop=True, inplace=True)
  200. df['date_time'] = df['date_time'].dt.strftime('%Y-%m-%d %H:%M:%S')
  201. return df
  202. # 示例使用
  203. ftp_params = {
  204. 'xxl' : {
  205. 'host' : '39.107.246.215',
  206. 'user' : 'jiayue',
  207. 'password' : 'JYoguf2018',
  208. 'remote_dir' : './',
  209. 'local_dir': 'data_processing/cache/data/xxl'
  210. }
  211. }
  212. def send_message(filename, text):
  213. """
  214. 1. 下载超时
  215. 2. 找不到nwp
  216. """
  217. url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=553f02de-0ef4-49ce-8d68-2489c032d42f"
  218. # 设置请求头
  219. headers = {'Content-Type': 'application/json'}
  220. text=f"""<font color=\'warning\'>算法平台解析nwp模块</font>
  221. >文件:<font color=\'comment\'>{filename}</font>\n
  222. >日志:<font color=\'comment\'> {text} \n</font> """
  223. # 设置消息内容
  224. data = {
  225. "msgtype": "markdown",
  226. "markdown": {
  227. "content": text
  228. }
  229. }
  230. # 发送POST请求
  231. response = requests.post(url, headers=headers, data=json.dumps(data))
  232. @app.route('/data_nwp_ftp', methods=['POST'])
  233. def get_nwp_from_ftp():
  234. # 获取程序开始时间
  235. start_time = time.time()
  236. result = {}
  237. success = False
  238. args = {}
  239. # print("data_nwp_ftp starts execution!")
  240. try:
  241. args = request.values.to_dict()
  242. # 1. 获取参数:日期,数据源,时刻,D0-9,场站ID,存储的 mongo 和表
  243. # print('args', args)
  244. logger.info(args)
  245. # 2. 连接FTP,从FTP服务器中获取指定参数的压缩文件(定时任务)
  246. # 3. 解压压缩文件,将其存储到mongo中
  247. date, moment = get_moment_next(args.get('dt'))
  248. logger.info("从日期{}时刻{}开始查找文件".format(date, moment))
  249. success = select_file_to_mongo(args, date, moment)
  250. new_date = date
  251. i = 1
  252. while not success and date == new_date and i <= 2:
  253. new_date, moment = get_previous_moment(date, moment)
  254. logger.info("未找到,从日期{}时刻{}开始查找文件".format(new_date, moment))
  255. success = select_file_to_mongo(args, new_date, moment)
  256. i += 1
  257. if not success:
  258. csv_file_weather = 'meteoforce_{}_{}_weather.csv'.format(args['farmId'], date + str(moment))
  259. logger_text = f"未找到 {csv_file_weather} 文件"
  260. logger.info(logger_text)
  261. send_message(csv_file_weather, logger_text)
  262. except Exception as e:
  263. my_exception = traceback.format_exc()
  264. my_exception.replace("\n", "\t")
  265. result['msg'] = my_exception
  266. logger.info("生产,获取原始nwp出错:{}".format(my_exception))
  267. end_time = time.time()
  268. result['success'] = success
  269. result['args'] = args
  270. result['start_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))
  271. result['end_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
  272. # print("Program execution ends!")
  273. return result
  274. if __name__ == "__main__":
  275. print("Program starts execution!")
  276. from waitress import serve
  277. update_thread() #定时任务开启
  278. # 遍历参数,创建并启动线程
  279. for moment in ['00', '06', '12', '18']:
  280. threading.Thread(target=download_zip_files_from_ftp, kwargs={'moment': moment}).start()
  281. serve(app, host="0.0.0.0", port=10102)
  282. print("server start!")
  283. # now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai"))
  284. # logger_text = f"下载完成时间:{now.strftime('%Y-%m-%d %H:%M:%S')},下载 20230323-meteoforece-nwp.zip 文件,用时 {700/60:.2f}分钟"
  285. # logger.info(logger_text)
  286. # send_message('20230323-meteoforece-nwp.zip', logger_text)
  287. # farmId, isDq = 'j01096', 1
  288. # date, moment = get_moment_next()
  289. # csv_file_weather = 'meteoforce_{}_{}_weather.csv'.format(farmId, date + str(moment))
  290. # logger_text = f"未找到 {csv_file_weather} 文件"
  291. # send_message(csv_file_weather, logger_text)