[Python] 纯文本查看 复制代码
import requests
import json
from datetime import datetime
import os
import traceback
# 配置基础信息
BASE_URL = "http://10.249.83.130/fsi/api/fileupload/download"
HEADERS = {
"x-ca-key": "H33021100190",
"x-ca-signature": "1745765307:B7225705884439223FA449163109573AA00F2B1980DF2F1DB5F3E4608953B235",
"Content-Type": "application/json;charset=UTF-8"
}
def log_error(message):
"""
将错误信息保存到桌面的 log 文件中。
参数:
message (str): 要记录的错误信息。
"""
desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
log_file_path = os.path.join(desktop_path, 'error_log.txt')
with open(log_file_path, "a") as log_file:
log_file.write(f"{datetime.now()}: {message}\n")
def send_post_request():
"""
发送 POST 请求并获取响应,处理返回结果。如果返回 JSON 数据且包含文件下载信息,
则调用 download_file 函数进行文件下载;否则将响应内容保存为 ZIP 文件。
请求体包含固定参数和输入数据,请求头使用全局定义的 BASE_URL 和 HEADERS。
"""
# 构造请求体
payload = {
"opter": "001",
"recer_sys_code": "FSI_LOCAL",
"msgid": "H33021100190202504272248277445",
"inf_time": "2025-04-27 22:48:27",
"input": {
"fsDownloadIn": {
"filename": "202201208777742551464510966.txt.zip",
"file_qury_no": "fsi/plc/6a93ab27602e440da8ca40cd4051c4",
"fixmedins_code": "H123"
}
},
"infno": "9102",
"cainfo": "",
"opter_type": "1",
"opter_name": "管理员",
"signtype": "SM3",
"dev_safe_info": "",
"insuplc_admdvs": "330211",
"mdtrtarea_admvs": "330211",
"infver": "V1.0",
"sign_no": "125878142",
"fixmedins_name": "测试",
"fixmedins_code": "H123",
"dev_no": ""
}
try:
# 发送 POST 请求
response = requests.post(BASE_URL, headers=HEADERS, data=json.dumps(payload))
response.raise_for_status() # 检查 HTTP 响应状态码
# 打印响应内容(调试用)
print("响应内容:", response.text)
# 检查 Content-Type
content_type = response.headers.get('Content-Type')
if content_type and 'application/json' in content_type:
# 解析响应内容
try:
response_data = response.json()
print("响应数据:", response_data)
# 提取文件下载信息
filename = response_data.get("output", {}).get("filename")
file_query_no = response_data.get("output", {}).get("file_qury_no")
if filename and file_query_no:
download_file(file_query_no, filename)
else:
print("未找到文件下载信息!")
log_error("未找到文件下载信息!")
except json.JSONDecodeError as e:
print("JSON 解析失败:", e)
log_error(f"JSON 解析失败: {e}\n响应内容: {response.text}")
else:
# 如果响应内容不是 JSON 格式,直接保存响应内容到文件
desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
target_path = os.path.join(desktop_path, "response_content.zip")
with open(target_path, "wb") as file:
file.write(response.content)
print(f"响应内容已保存到: {target_path}")
log_error(f"响应内容不是 JSON 格式,已保存到: {target_path}")
except requests.exceptions.RequestException as e:
print("请求失败:", e)
traceback.print_exc()
log_error(f"请求失败: {e}\n响应内容: {response.text if 'response' in locals() else '无'}\n{traceback.format_exc()}")
except Exception as e:
print("发生错误:", e)
traceback.print_exc()
log_error(f"发生错误: {e}\n响应内容: {response.text if 'response' in locals() else '无'}\n{traceback.format_exc()}")
def download_file(file_query_no, filename):
"""
根据文件查询号下载文件并保存到桌面。
参数:
file_query_no (str): 文件查询编号,用于构造下载 URL。
filename (str): 下载文件的名称,用于本地保存。
返回值:
None
"""
download_url = f"{BASE_URL}/{file_query_no}"
try:
with requests.get(download_url, headers=HEADERS, stream=True) as response:
response.raise_for_status()
# 获取桌面路径
desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
target_path = os.path.join(desktop_path, filename)
# 保存文件到桌面
with open(target_path, "wb") as file:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
file.write(chunk)
print(f"文件已保存到桌面: {target_path}")
except requests.exceptions.RequestException as e:
print("文件下载失败:", e)
traceback.print_exc()
log_error(f"文件下载失败: {e}\n{traceback.format_exc()}")
except Exception as e:
print("发生错误:", e)
traceback.print_exc()
log_error(f"发生错误: {e}\n{traceback.format_exc()}")
if __name__ == "__main__":
"""
程序入口点,调用 send_post_request 函数发送请求,并捕获主程序异常。
最后等待用户按 Enter 键退出控制台。
"""
try:
send_post_request()
except Exception as e:
print("主程序发生错误:", e)
traceback.print_exc()
log_error(f"主程序发生错误: {e}\n{traceback.format_exc()}")
# 保持控制台窗口打开
input("按 Enter 键退出...")