You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将指定curl命令转为Python requests实现时遇文件损坏问题求助

问题解决与自动化UI实现

一、修复文件损坏问题

你的代码核心逻辑没问题,但可能因为未处理请求异常、文件资源未正确释放或未校验响应状态导致文件损坏。以下是修复后的代码:

import requests

# 配置参数
API_URL = "http://pury.fi/censor"
params = {
    'type': 'pixel',
    'classes': 'ftite,fgene,fgenc'
}

# 用with语句确保文件正确关闭
try:
    with open('infile.jpg', 'rb') as img_file:
        files = {'file': img_file}
        # 发送请求并校验状态码
        response = requests.post(API_URL, params=params, files=files)
        response.raise_for_status()  # 若请求失败(非200状态码)抛出异常

        # 写入输出文件
        with open('outfile.jpg', 'wb') as out_file:
            out_file.write(response.content)
        print("处理完成,文件已保存为outfile.jpg")

except requests.exceptions.RequestException as e:
    print(f"请求出错: {e}")
    # 打印响应内容排查错误(如果是文本错误信息)
    if response.text:
        print(f"响应内容: {response.text}")
except FileNotFoundError:
    print("错误:未找到infile.jpg文件")
except Exception as e:
    print(f"其他错误: {e}")

关键修复点:

  • 使用with语句管理文件资源,避免文件未正确关闭导致的损坏
  • 添加response.raise_for_status()校验请求是否成功,若API返回错误(如参数错误、文件格式不支持)会直接抛出异常
  • 增加异常捕获,便于排查具体错误(比如文件不存在、网络问题、API返回错误信息)

二、添加图形化UI(基于tkinter)

下面是集成了文件选择、一键处理的桌面UI版本,无需手动修改文件名:

import requests
import tkinter as tk
from tkinter import filedialog, messagebox

def process_image():
    # 选择输入文件
    input_path = filedialog.askopenfilename(
        title="选择要处理的图片",
        filetypes=[("JPEG图片", "*.jpg"), ("所有文件", "*.*")]
    )
    if not input_path:
        return

    # 选择输出文件保存路径
    output_path = filedialog.asksaveasfilename(
        title="保存处理后的图片",
        defaultextension=".jpg",
        filetypes=[("JPEG图片", "*.jpg"), ("所有文件", "*.*")]
    )
    if not output_path:
        return

    # 发送请求处理图片
    API_URL = "http://pury.fi/censor"
    params = {
        'type': 'pixel',
        'classes': 'ftite,fgene,fgenc'
    }

    try:
        with open(input_path, 'rb') as img_file:
            files = {'file': img_file}
            response = requests.post(API_URL, params=params, files=files)
            response.raise_for_status()

            with open(output_path, 'wb') as out_file:
                out_file.write(response.content)
        messagebox.showinfo("成功", "图片处理完成,已保存到指定路径!")
    except requests.exceptions.RequestException as e:
        error_msg = f"请求失败: {str(e)}"
        if response.text:
            error_msg += f"\nAPI返回信息: {response.text}"
        messagebox.showerror("错误", error_msg)
    except Exception as e:
        messagebox.showerror("错误", f"处理失败: {str(e)}")

# 创建UI窗口
root = tk.Tk()
root.title("图片敏感内容处理工具")
root.geometry("350x150")

# 添加按钮
process_btn = tk.Button(root, text="选择图片并处理", command=process_image, width=20, height=2)
process_btn.pack(pady=50)

root.mainloop()

UI功能说明:

  • 点击按钮可选择本地要处理的图片文件
  • 可自定义处理后图片的保存路径和文件名
  • 处理成功/失败都会弹出提示框,错误时会显示具体原因

内容的提问来源于stack exchange,提问作者user19941204

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:50:24