data_nwp_ftp.py 11 KB

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