开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 101|回复: 1
收起左侧

[易语言] python转易语言代码

[复制链接]
结帖率:97% (60/62)
发表于 4 小时前 | 显示全部楼层 |阅读模式   浙江省宁波市
30精币
[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 键退出...")


回答提醒:如果本帖被关闭无法回复,您有更好的答案帮助楼主解决,请发表至 源码区 可获得加分喔。
友情提醒:本版被采纳的主题可在 申请荣誉值 页面申请荣誉值,获得 1点 荣誉值,荣誉值可兑换荣誉会员、终身vip用户组。
快捷通道:申请荣誉值

签到天数: 7 天

发表于 3 小时前 | 显示全部楼层   河南省安阳市
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报QQ: 793400750,邮箱:wp@125.la
网站简介:精易论坛成立于2009年,是一个程序设计学习交流技术论坛,隶属于揭阳市揭东区精易科技有限公司所有。
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备2025452707号) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表