zbparse/flask_app/routes/little_zbparse.py
2024-12-05 15:01:37 +08:00

77 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# flask_app/routes/little_zbparse.py
import json
import os
from flask import Blueprint, jsonify, g
from flask_app.ConnectionLimiter import require_connection_limit
from flask_app.general.format_change import download_file
from flask_app.routes.接口_小解析 import little_parse_main
from flask_app.routes.utils import validate_and_setup_logger
little_zbparse_bp = Blueprint('little_zbparse', __name__)
@little_zbparse_bp.route('/little_zbparse', methods=['POST'])
@validate_and_setup_logger
@require_connection_limit(timeout=300)
def little_zbparse():
logger = g.logger
file_url = g.file_url
zb_type = g.zb_type
if isinstance(file_url, tuple): # 检查是否为错误响应
return file_url
try:
logger.info("starting parsing url:" + file_url)
final_json_path = download_and_process_file(file_url, zb_type)
if not final_json_path:
return jsonify({'error': 'File processing failed'}), 500
response = generate_response(final_json_path)
return response
except Exception as e:
logger.error('Exception occurred: ' + str(e))
return jsonify({'error': str(e)}), 500
def download_and_process_file(file_url, zb_type):
"""
下载并处理文件根据zb_type选择处理函数。
参数:
file_url (str): 文件的URL地址。
zb_type (int): 标的类型1表示工程标2表示货物标。
返回:
str: 处理后的文件路径。
"""
logger = g.logger
output_folder = g.output_folder
filename = "ztbfile"
downloaded_filename = os.path.join(output_folder, filename)
downloaded_filepath, file_type = download_file(file_url, downloaded_filename)
if downloaded_filepath is None or file_type == 4:
logger.error("Unsupported file type or failed to download file")
return None
logger.info("Local file path: " + downloaded_filepath)
processed_file_path = little_parse_main(output_folder, downloaded_filepath, file_type, zb_type, g.unique_id)
return processed_file_path
def generate_response(final_json_path):
logger = g.logger
if not final_json_path:
logger.error('Empty or None path provided for final_json.')
return jsonify({'error': 'No path provided for final_json.'}), 400
if not os.path.exists(final_json_path):
logger.error('final_json not found at path: ' + final_json_path)
return jsonify({'error': 'final_json not found'}), 404
with open(final_json_path, 'r', encoding='utf-8') as f:
zbparse_data = json.load(f)
json_str = json.dumps(zbparse_data, ensure_ascii=False)
return jsonify({
'message': 'Little Parse processed successfully',
'filename': os.path.basename(final_json_path),
'data': json_str
})