data_nwp_ftp.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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=False):
  63. if schedule_dt:
  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. if now.hour == 18:
  68. moment = '18'
  69. elif now.hour > 18:
  70. moment = '00'
  71. elif now.hour == 12:
  72. moment = '12'
  73. elif now.hour > 12:
  74. moment = '18'
  75. elif now.hour == 6:
  76. moment = '06'
  77. elif now.hour > 6:
  78. moment = '12'
  79. elif 2 >= now.hour >= 0:
  80. moment = '00'
  81. else:
  82. moment = '06'
  83. return moment
  84. def get_moment(schedule_dt=False):
  85. if schedule_dt:
  86. now = datetime.datetime.strptime(str(schedule_dt), '%Y-%m-%d %H:%M:%S')
  87. else:
  88. now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai"))
  89. if now.hour >= 18:
  90. moment = '18'
  91. elif now.hour >= 12:
  92. moment = '12'
  93. elif now.hour >= 6:
  94. moment = '06'
  95. else:
  96. moment = '00'
  97. return moment
  98. def download_zip_files_from_ftp(moment=None):
  99. now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai"))
  100. date = now.strftime("%Y%m%d")
  101. date_2 = (now - timedelta(days=2)).strftime("%Y%m%d")
  102. if moment is None:
  103. moment = get_moment_next()
  104. host = 'xxl'
  105. 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']
  106. zip_extension = f'meteoforce_{date}{str(moment)}_*.zip'
  107. zip_file_path = []
  108. # 连接到FTP服务器
  109. with FTP(ftp_host) as ftp:
  110. ftp.login(user=ftp_user, passwd=ftp_password)
  111. # 切换到远程目录
  112. ftp.cwd(remote_dir)
  113. # 获取远程目录中的文件和目录列表
  114. files = ftp.nlst()
  115. # 遍历文件列表,找到ZIP文件并下载
  116. for file_name in files:
  117. if fnmatch.fnmatch(file_name, zip_extension):
  118. remote_file_path = os.path.join(remote_dir, file_name)
  119. local_file_path = os.path.join(local_dir, file_name)
  120. if os.path.isfile(local_file_path):
  121. continue
  122. with open(local_file_path, 'wb') as local_file:
  123. logger.info(f"Downloading {remote_file_path} to {local_file_path}")
  124. ftp.retrbinary(f'RETR {remote_file_path}', local_file.write)
  125. logger.info(f"Downloaded {file_name}")
  126. zip_file_path.append(local_file_path)
  127. # 解压 ZIP 文件到临时目录
  128. for zip_file_p in zip_file_path:
  129. with zipfile.ZipFile(zip_file_p, 'r') as zip_ref:
  130. zip_ref.extractall(local_dir)
  131. # 删除前天之前所有 ZIP 文件
  132. delete_zip_files(date_2)
  133. def select_file_to_mongo(args):
  134. date, moment, farmId, isDq = args['dt'], get_moment_next(args['dt']), args['farmId'], args['isDq']
  135. date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').strftime("%Y%m%d")
  136. csv_file_format = 'meteoforce_{}_{}_*.csv'.format(farmId, date + str(moment))
  137. csv_file_weather = csv_file_format.replace('*', 'weather')
  138. csv_file_power = csv_file_format.replace('*', 'power')
  139. csv_weather_path, csv_power_path = False, False
  140. # 查找目标目录并读取 CSV 文件
  141. for root, dirs, files in os.walk(ftp_params['xxl']['local_dir']):
  142. if farmId in dirs:
  143. target_dir_path = os.path.join(root, farmId)
  144. for file_name in os.listdir(target_dir_path):
  145. csv_file_path = os.path.join(target_dir_path, file_name)
  146. if fnmatch.fnmatch(file_name, csv_file_weather):
  147. csv_weather_path = csv_file_path
  148. logger.info("找到nwp:{}".format(csv_weather_path))
  149. if fnmatch.fnmatch(file_name, csv_file_power):
  150. csv_power_path = csv_file_path
  151. logger.info("找到power:{}".format(csv_power_path))
  152. if csv_weather_path or csv_power_path:
  153. break
  154. if csv_weather_path is False:
  155. raise ValueError("获取nwp文件异常:找不到文件")
  156. # 使用 pandas 读取 CSV 文件
  157. weather = pd.read_csv(csv_weather_path)
  158. power = pd.read_csv(csv_power_path) if csv_power_path else None
  159. if isDq:
  160. if csv_weather_path and csv_power_path:
  161. power.drop(columns=['farm_id'], inplace=True)
  162. weather_power = pd.merge(weather, power, on='date_time')
  163. # 截取D0-D13时段数据
  164. df = select_dx_from_nwp(weather_power, args)
  165. insert_data_into_mongo(df, args)
  166. else:
  167. df = select_dx_from_nwp(weather, args)
  168. insert_data_into_mongo(df, args)
  169. logger.info(f"CSV 文件 {csv_file_power} 或 {csv_file_weather} 在目标目录 {farmId} 中未找到")
  170. else:
  171. if csv_weather_path:
  172. weather = select_dx_from_nwp(weather, args)
  173. # 截取D0-D13时段数据
  174. df = select_dx_from_nwp(weather, args)
  175. insert_data_into_mongo(df, args)
  176. else:
  177. logger.info(f"CSV 文件 {csv_file_weather} 在目标目录 {farmId} 中未找到")
  178. def select_dx_from_nwp(df, args):
  179. date = datetime.datetime.strptime(args['dt'], '%Y-%m-%d %H:%M:%S')
  180. date_begin = date + pd.Timedelta(days=int(args.get('day_begin', 'D0')[1:]))
  181. date_end = date + pd.Timedelta(days=int(args.get('day_end', 'D13')[1:]))
  182. df['date_time'] = df['date_time'].str.replace("_", " ")
  183. df['date_time'] = pd.to_datetime(df['date_time'])
  184. df.set_index('date_time', inplace=True)
  185. df = df.loc[date_begin.strftime('%Y-%m-%d'): date_end.strftime('%Y-%m-%d')].reset_index(drop=False)
  186. df.reset_index(drop=True, inplace=True)
  187. df['date_time'] = df['date_time'].dt.strftime('%Y-%m-%d %H:%M:%S')
  188. return df
  189. # 示例使用
  190. ftp_params = {
  191. 'xxl' : {
  192. 'host' : '39.107.246.215',
  193. 'user' : 'jiayue',
  194. 'password' : 'JYoguf2018',
  195. 'remote_dir' : './',
  196. 'local_dir': 'data_processing/cache/data/xxl'
  197. }
  198. }
  199. @app.route('/data_nwp_ftp', methods=['POST'])
  200. def get_nwp_from_ftp():
  201. # 获取程序开始时间
  202. start_time = time.time()
  203. result = {}
  204. success = 0
  205. args = {}
  206. # print("data_nwp_ftp starts execution!")
  207. try:
  208. now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai")).strftime('%Y-%m-%d %H:%M:%S')
  209. args = request.values.to_dict()
  210. if args.get('dt') is None:
  211. args['dt'] = now
  212. # 1. 获取参数:日期,数据源,时刻,D0-9,场站ID,存储的 mongo 和表
  213. # print('args', args)
  214. logger.info(args)
  215. # 2. 连接FTP,从FTP服务器中获取指定参数的压缩文件(定时任务)
  216. # 3. 解压压缩文件,将其存储到mongo中
  217. select_file_to_mongo(args)
  218. success = 1
  219. except Exception as e:
  220. my_exception = traceback.format_exc()
  221. my_exception.replace("\n", "\t")
  222. result['msg'] = my_exception
  223. logger.info("生产,获取原始nwp出错:{}".format(my_exception))
  224. end_time = time.time()
  225. result['success'] = success
  226. result['args'] = args
  227. result['start_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))
  228. result['end_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
  229. # print("Program execution ends!")
  230. return result
  231. if __name__ == "__main__":
  232. print("Program starts execution!")
  233. from waitress import serve
  234. update_thread() #定时任务开启
  235. current_hour = '06' # 默认首次运行下载06时刻的zip
  236. threading.Thread(target=download_zip_files_from_ftp, kwargs={'moment': current_hour}).start()
  237. serve(app, host="0.0.0.0", port=10102)
  238. print("server start!")
  239. # args = {"source": 'xxl', "date": '2024-12-27', 'moment': '06', 'farmId': 'J00645',
  240. # 'mongodb_database': 'db2', 'mongodb_write_table': 'j00645-d1', 'day_begin':'D0',
  241. # 'day_end': 'D13', 'isDq': True}
  242. # download_zip_files_from_ftp(hour='06')
  243. # select_file_to_mongo(args)
  244. # delete_zip_files('20241225')