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

Python requests发POST请求传CSV到Postman报422错误如何解决

问题原因

422报错的核心原因是对requests库的参数使用规则理解错误:

  • 调用requests.post()传入files参数时,请求会自动以multipart/form-data格式编码,所有放在files字典中的键值对都会被识别为文件上传字段,无论传入的是字符串、数字还是文件对象。
  • 你把template_id、entity、simulation这类普通表单参数和文件字段一起塞进了files字典,服务端解析表单时会把这些字段判定为上传文件条目,而不是普通字符串参数,自然读取不到符合要求的entity字符串值,触发校验报错。
  • Postman GUI手动操作能正常传输,是因为Postman会自动区分普通表单项和文件上传项,不会把普通字段按文件格式编码,和你代码的请求编码逻辑不一样。
  • 之前尝试把整型参数转字符串、移除对应参数都无法解决问题,本质是参数传递的位置错误,和字段值的类型没有关系。
修复方案

将普通表单字段和文件上传字段拆分传递:文件相关字段传入files参数,其余普通非文件字段传入data参数即可。

从pandas DataFrame生成CSV上传的正确实现

import requests
import pandas as pd

# 生成CSV字节流,关闭索引避免多余列,指定编码防止乱码
csv_content = df.to_csv(index=False).encode('utf-8')
url = 'url.com'
headers = {'Authorization': 'my password'}

# 普通表单字段放在data参数中
form_data = {
    'template_id': 3,
    'entity': 'product',
    'simulation': 0
}

# 仅文件字段放在files参数中,按(文件名, 文件内容, MIME类型)格式传递
upload_files = {
    'file': ('data_export.csv', csv_content, 'text/csv')
}

response = requests.post(url, headers=headers, data=form_data, files=upload_files)
print(response.json())

读取本地CSV文件上传的正确实现

import requests

url = 'url.com'
headers = {'Authorization': 'my password'}

# 普通表单字段放在data参数中
form_data = {
    'template_id': 3,
    'entity': 'product',
    'simulation': 0
}

# 用上下文管理器打开文件,自动释放资源,仅文件字段传入files
with open('file.csv', 'rb') as f:
    upload_files = {
        'file': ('file.csv', f, 'text/csv')
    }
    response = requests.post(url, headers=headers, data=form_data, files=upload_files)
print(response.json())

注意事项:不要手动在headers中添加Content-Type: multipart/form-data,requests传入files参数时会自动生成带正确boundary边界值的请求头,手动添加反而会因为缺失boundary导致请求解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 16:01:07