pre_data_ftp.py 5.3 KB

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