zbparse/flask_app/routes/little_zbparse.py

137 lines
4.2 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.小解析main import little_parse_main
from flask_app.routes.utils import validate_and_setup_logger
little_zbparse_bp = Blueprint('little_zbparse', __name__)
def create_response(message, status, data='', status_code=200):
"""
创建统一格式的 JSON 响应。
参数:
message (str): 响应消息。
status (str): 状态标记,'success''error'
data (str, optional): 响应数据。默认为空字符串。
status_code (int, optional): HTTP 状态码。默认为 200。
返回:
Response: Flask 响应对象。
"""
response = jsonify({
'message': message,
'status': status,
'data': data
})
response.status_code = status_code
return response
@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(f"Starting parsing URL: {file_url}")
final_json_path = download_and_process_file(file_url, zb_type)
if not final_json_path:
return create_response(
message='上传的文件非招标文件或文件内容不完整!',
status='error',
data='',
status_code=400 # 400 Bad Request
)
response = generate_response(final_json_path)
return response
except Exception as e:
logger.error(f'Exception occurred: {e}')
return create_response(
message='解析遇到不知名错误!',
status='error',
data='',
status_code=500 # 500 Internal Server Error
)
def download_and_process_file(file_url, zb_type):
"""
下载并处理文件,根据 zb_type 选择处理函数。
参数:
file_url (str): 文件的 URL 地址。
zb_type (int): 标的类型1 表示工程标2 表示货物标。
返回:
str or None: 处理后的文件路径,或在失败时返回 None。
"""
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(f"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):
"""
生成最终的成功响应或错误响应。
参数:
final_json_path (str): 处理后的 JSON 文件路径。
返回:
tuple: Flask 响应对象和状态码。
"""
logger = g.logger
if not os.path.exists(final_json_path):
logger.error(f'final_json 未找到!: {final_json_path}')
return create_response(
message='final_json not found',
status='error',
data='',
status_code=404 # 404 Not Found
)
try:
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)
except Exception as e:
logger.error(f'Error reading or parsing final_json: {e}')
return create_response(
message='Error processing final_json.',
status='error',
data='',
status_code=500 # 500 Internal Server Error
)
return create_response(
message='Little Parse processed successfully',
status='success',
data=json_str,
status_code=200 # 200 OK
)