pre_data_ftp.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # @FileName :pre_data_ftp.py
  4. # @Time :2024/12/26 14:18
  5. # @Author :David
  6. # @Company: shenyang JY
  7. from ftplib import FTP
  8. import pandas as pd
  9. from flask import Flask, request, jsonify
  10. import time, datetime, os, traceback, pytz
  11. from pytz import timezone
  12. import zipfile, tempfile, shutil
  13. from common.database_dml import get_data_from_mongo
  14. from common.logs import Log
  15. logger = Log('data-processing').logger
  16. app = Flask('pre_data_ftp——service')
  17. ftp_params = {
  18. 'local_dir' : './data_processing/cache/data',
  19. 'host' : '192.168.12.20',
  20. 'port': 32121,
  21. 'zip_mode': 'w',
  22. 'liudawei' : {
  23. 'user' : 'liudawei',
  24. 'password' : 'liudawei@123',
  25. 'modeler' : 'koi'
  26. },
  27. 'anweiguo':{
  28. 'user' : 'anweiguo',
  29. 'password' : 'anweiguo@123',
  30. 'modeler' : 'seer'
  31. }
  32. }
  33. def get_moment_next(schedule_dt=False):
  34. if schedule_dt:
  35. now = datetime.datetime.strptime(str(schedule_dt), '%Y-%m-%d %H:%M:%S')
  36. else:
  37. now = datetime.datetime.now(pytz.utc).astimezone(timezone("Asia/Shanghai"))
  38. date = now.strftime('%Y%m%d')
  39. if now.hour == 18:
  40. moment = '18'
  41. elif now.hour > 18:
  42. moment = '00'
  43. elif now.hour == 12:
  44. moment = '12'
  45. elif now.hour > 12:
  46. moment = '18'
  47. elif now.hour == 6:
  48. moment = '06'
  49. elif now.hour > 6:
  50. moment = '12'
  51. elif 2 >= now.hour >= 0:
  52. moment = '00'
  53. else:
  54. moment = '06'
  55. return date, moment
  56. def zip_temp_file(df, args):
  57. def zip_folder(folder_path, zip_filePath):
  58. zip_file = zipfile.ZipFile(zip_filePath, ftp_params['zip_mode'], zipfile.ZIP_DEFLATED)
  59. for root, dirs, files in os.walk(folder_path):
  60. for file in files:
  61. file_path = os.path.join(root, file)
  62. zip_file.write(file_path, os.path.relpath(file_path, folder_path))
  63. zip_file.close()
  64. temp_dir, tem_dir_zip = tempfile.mkdtemp(dir=ftp_params['local_dir']), tempfile.mkdtemp(dir=ftp_params['local_dir'])
  65. date, moment = get_moment_next() if args.get('dt') is None else get_moment_next(args.get('dt'))
  66. modeler, model, version, farmId = ftp_params[args['user']]['modeler'], args['model'], args['version'], args['farmId']
  67. csv_file = 'jy_{}.{}.{}_{}_{}{}_dq.csv'.format(modeler, model, version, farmId, date, moment)
  68. csv_path = os.path.join(temp_dir, farmId, csv_file)
  69. os.makedirs(os.path.dirname(csv_path), exist_ok=True)
  70. df.to_csv(csv_path, index=False)
  71. zip_file = 'jy_{}.{}.{}_{}{}_dq.zip'.format(modeler, model, version, date, moment)
  72. zip_path = os.path.join(tem_dir_zip, zip_file)
  73. zip_folder(temp_dir, zip_path)
  74. shutil.rmtree(temp_dir)
  75. return zip_path, zip_file
  76. def upload_ftp(zip_path, zip_file, args):
  77. ftp_host, ftp_port, ftp_user, ftp_pass = ftp_params['host'], ftp_params['port'], args['user'], ftp_params[args['user']]['password']
  78. # 创建 FTP 连接
  79. ftp = FTP()
  80. # 使用被动模式
  81. ftp.set_pasv(True)
  82. # 连接到 FTP 服务器并指定端口
  83. ftp.connect(ftp_host, ftp_port) # 使用自定义端口号
  84. # 登录到 FTP 服务器
  85. ftp.login(ftp_user, ftp_pass)
  86. # 上传文件
  87. with open(zip_path, 'rb') as f:
  88. ftp.storbinary('STOR /' + ftp_params[args['user']]['modeler'] + '/'+zip_file, f)
  89. # 退出 FTP 连接
  90. ftp.quit()
  91. shutil.rmtree(os.path.dirname(zip_path))
  92. # os.remove(zip_path)
  93. logger.info("File uploaded successfully")
  94. @app.route('/pre_data_ftp', methods=['POST'])
  95. def get_nwp_from_ftp():
  96. # 获取程序开始时间
  97. start_time = time.time()
  98. result = {}
  99. success = 0
  100. args = {}
  101. try:
  102. args = request.values.to_dict()
  103. # 1. 获取 mongo 中的预测结果
  104. logger.info(args)
  105. df = get_data_from_mongo(args)
  106. df['date_time'] = pd.to_datetime(df['date_time'])
  107. df = df.sort_values(by='date_time')[['farm_id', 'date_time', 'power_forecast']]
  108. # 2. 将预测结果保存成csv临时文件,命名压缩
  109. zip_path, zip_file = zip_temp_file(df, args)
  110. # 3. 上传到指定的FTP服务器中
  111. upload_ftp(zip_path, zip_file, args)
  112. success = 1
  113. except Exception as e:
  114. my_exception = traceback.format_exc()
  115. my_exception.replace("\n", "\t")
  116. result['msg'] = my_exception
  117. logger.info("预测文件下发ftp出错:{}".format(my_exception))
  118. end_time = time.time()
  119. result['success'] = success
  120. result['args'] = args
  121. result['start_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))
  122. result['end_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
  123. return result
  124. if __name__ == "__main__":
  125. print("Program starts execution!")
  126. from waitress import serve
  127. serve(app, host="0.0.0.0", port=10101)
  128. print("server start!")
  129. # args = {"user": 'anweiguo', 'model': 'Zone', 'version': 1.0, 'hour': '06',
  130. # 'farmId': 'J00645', 'mongodb_database': 'db2', 'mongodb_read_table': 'j00645_ori_res', 'day_begin':'D1',
  131. # 'day_end': 'D1'}
  132. # df = get_data_from_mongo(args)
  133. # df.rename(columns={'dateTime': 'date_time'}, inplace=True)
  134. # df['date_time'] = pd.to_datetime(df['date_time'])
  135. # zip_path, zip_file = zip_temp_file(df, args)
  136. # upload_ftp(zip_path, zip_file, args)