读取CSV文件创建User时触发MultiValueDictKeyError问题求助
读取CSV文件创建用户时触发MultiValueDictKeyError错误
我尝试读取CSV文件批量创建用户,但调用/api/user/接口时触发了MultiValueDictKeyError错误,运行结果显示用户创建失败。
我的代码如下:
def read_and_create_csv_file(): header = {'Authorization': f'Token {get_token()}'} url = f"{URL}/api/user/" with open(r"E:\WC_API\employees.csv") as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: data = { "USERNAME": row['username'], "FIRST_NAME": row['FIRST_NAME'], "LAST_NAME": row['LAST_NAME'], "EMAIL": row["EMAIL"], "PASSWORD": "Abc@123"} response = requests.post(url, json=data, headers=header) if response.status_code == 201: print("User created successfully") else: print("Failed to create user") read_and_create_csv_file()
运行结果:
Failed to create user or MultiValueDictKeyError
问题排查与解决方法
1. 核对CSV表头与代码键名的一致性
MultiValueDictKeyError大多是因为代码中引用的字段在CSV表头里不存在,或者大小写、拼写不匹配:
- 打开
employees.csv确认表头是否包含username、FIRST_NAME、LAST_NAME、EMAIL,注意大小写敏感(比如代码用row['username']但CSV表头是Username就会报错)。 - 可以在循环前打印实际读取到的表头,快速验证:
print(csv_reader.fieldnames) # 放在for row in csv_reader之前
2. 处理CSV中的缺失字段
如果某行CSV缺少必填字段,直接访问row['xxx']会触发错误,建议用row.get()替代,并添加校验逻辑:
data = { "USERNAME": row.get('username'), "FIRST_NAME": row.get('FIRST_NAME'), "LAST_NAME": row.get('LAST_NAME'), "EMAIL": row.get("EMAIL"), "PASSWORD": "Abc@123" } # 必填字段为空则跳过当前行 if not data["USERNAME"] or not data["EMAIL"]: print(f"跳过无效行:{row}") continue
3. 匹配接口接收的参数格式
- 若后端接口要求接收表单数据而非JSON,把
json=data改成data=data:response = requests.post(url, data=data, headers=header) - 查接口文档确认参数键名的大小写、命名是否和你发送的一致(比如后端要求
username小写,你传USERNAME大写会导致参数无法识别)。
4. 打印响应详情定位错误
在请求后打印后端返回的内容,能直接看到具体错误原因:
response = requests.post(url, json=data, headers=header) print(f"状态码:{response.status_code}") print(f"响应内容:{response.text}")
内容的提问来源于stack exchange,提问作者AVINASH SRIVASTAVA
相关产品推荐
相关产品推荐

