pre_data_ftp.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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
  11. import logging, zipfile, tempfile, shutil
  12. from common.database_dml import get_data_from_mongo
  13. app = Flask('pre_data_ftp——service')
  14. ftp_params = {
  15. 'host' : '192.168.12.20',
  16. 'port': 32121,
  17. 'zip_mode': 'w',
  18. 'liudawei' : {
  19. 'user' : 'liudawei',
  20. 'password' : 'liudawei@123',
  21. 'modeler' : 'koi'
  22. },
  23. 'anweiguo':{
  24. 'user' : 'anweiguo',
  25. 'password' : 'anweiguo@123',
  26. 'modeler' : 'seer'
  27. }
  28. }
  29. def zip_temp_file(df, args):
  30. def zip_folder(folder_path, zip_filePath):
  31. zip_file = zipfile.ZipFile(zip_filePath, ftp_params['zip_mode'], zipfile.ZIP_DEFLATED)
  32. for root, dirs, files in os.walk(folder_path):
  33. for file in files:
  34. file_path = os.path.join(root, file)
  35. zip_file.write(file_path, os.path.relpath(file_path, folder_path))
  36. zip_file.close()
  37. temp_dir, tem_dir_zip = tempfile.mkdtemp(dir='../cache/data'), tempfile.mkdtemp(dir='../cache/data')
  38. dt = datetime.datetime.now().strftime('%Y%m%d')
  39. modeler, model, version, farmId, moment = ftp_params[args['user']]['modeler'], args['model'], args['version'], args['farmId'], args['moment']
  40. csv_file = 'jy_{}.{}.{}_{}_{}{}_dq.csv'.format(modeler, model, version, farmId, dt, moment)
  41. csv_path = os.path.join(temp_dir, farmId, csv_file)
  42. os.makedirs(os.path.dirname(csv_path), exist_ok=True)
  43. df.to_csv(csv_path, index=False)
  44. zip_file = 'jy_{}.{}.{}_{}{}_dq.zip'.format(modeler, model, version, dt, moment)
  45. zip_path = os.path.join(tem_dir_zip, zip_file)
  46. zip_folder(temp_dir, zip_path)
  47. shutil.rmtree(temp_dir)
  48. return zip_path, zip_file
  49. def upload_ftp(zip_path, zip_file, args):
  50. ftp_host, ftp_port, ftp_user, ftp_pass = ftp_params['host'], ftp_params['port'], args['user'], ftp_params[args['user']]['password']
  51. # 创建 FTP 连接
  52. ftp = FTP()
  53. # 使用主动模式
  54. ftp.set_pasv(False)
  55. # 连接到 FTP 服务器并指定端口
  56. ftp.connect(ftp_host, ftp_port) # 使用自定义端口号
  57. # 登录到 FTP 服务器
  58. ftp.login(ftp_user, ftp_pass)
  59. # 上传文件
  60. with open(zip_path, 'rb') as f:
  61. ftp.storbinary('STOR /' + ftp_params[args['user']]['modeler'] + '/'+zip_file, f)
  62. # 退出 FTP 连接
  63. ftp.quit()
  64. shutil.rmtree(os.path.dirname(zip_path))
  65. # os.remove(zip_path)
  66. print("File uploaded successfully")
  67. @app.route('/pre_data_ftp', methods=['POST'])
  68. def get_nwp_from_ftp():
  69. # 获取程序开始时间
  70. start_time = time.time()
  71. result = {}
  72. success = 0
  73. args = {}
  74. print("Program starts execution!")
  75. try:
  76. args = request.values.to_dict()
  77. # 1. 获取 mongo 中的预测结果
  78. print('args', args)
  79. logger.info(args)
  80. df = get_data_from_mongo(args)
  81. df['date_time'] = pd.to_datetime(df['date_time'])
  82. df = df.sort_values(by='date_time')
  83. # 2. 将预测结果保存成csv临时文件,命名压缩
  84. zip_path, zip_file = zip_temp_file(df, args)
  85. # 3. 上传到指定的FTP服务器中
  86. upload_ftp(zip_path, zip_file, args)
  87. success = 1
  88. except Exception as e:
  89. my_exception = traceback.format_exc()
  90. my_exception.replace("\n", "\t")
  91. result['msg'] = my_exception
  92. end_time = time.time()
  93. result['success'] = success
  94. result['args'] = args
  95. result['start_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))
  96. result['end_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
  97. print("Program execution ends!")
  98. return result
  99. if __name__ == "__main__":
  100. print("Program starts execution!")
  101. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  102. logger = logging.getLogger("pre_data_ftp")
  103. from waitress import serve
  104. serve(app, host="0.0.0.0", port=10101)
  105. print("server start!")
  106. # args = {"user": 'anweiguo', 'model': 'Zone', 'version': 1.0, 'hour': '06',
  107. # 'farmId': 'J00645', 'mongodb_database': 'db2', 'mongodb_read_table': 'J00645_tmp_w', 'day_begin':'D1',
  108. # 'day_end': 'D1'}
  109. # df = get_data_from_mongo(args)
  110. # df.rename(columns={'dateTime': 'date_time'}, inplace=True)
  111. # df['date_time'] = pd.to_datetime(df['date_time'])
  112. # zip_path, zip_file = zip_temp_file(df, args)
  113. # upload_ftp(zip_path, zip_file, args)