data_nwp_ftp.py 11 KB

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