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

Python如何实现POST请求提交数据与响应数据的比对校验

POST提交数据与接口返回值校验实现

原有代码问题

原有校验函数逻辑完全错误:直接对比两个固定字符串'priceCents'和'price',永远不会得到相等的结果,没有实际读取提交的参数值和接口返回值做比对。另外原代码中print(response_data['priceCents')存在语法笔误,缺少字段名的闭合引号,正确写法为print(response_data['priceCents'])。

可直接使用的校验代码

import requests
import json

# 构造POST请求参数
post_data = {
    'price': 16000,
    'overpriced_email_price_change': False,
    'apply_to_all': False,
}

# 发送POST请求
response = requests.post('apiurl', cookies=cookies, headers=headers, json=post_data)
response_data = json.loads(response.text)

def check_status(post_data, response_data):
    # 配置提交字段与接口返回字段的映射关系:key为提交参数字段名,value为对应返回字段名
    field_mapping = {
        'price': 'priceCents',
        'overpriced_email_price_change': 'overpriced_email_price_change',
        'apply_to_all': 'apply_to_all'
    }
    error_list = []

    # 逐字段校验
    for submit_field, resp_field in field_mapping.items():
        # 先判断返回数据是否存在对应字段,避免KeyError
        if resp_field not in response_data:
            error_list.append(f"返回数据缺失字段:{resp_field}")
            continue
        # 比对字段值是否一致
        if post_data[submit_field] != response_data[resp_field]:
            error_list.append(f"字段[{submit_field}]提交值为{post_data[submit_field]},返回值为{response_data[resp_field]},二者不匹配")

    if len(error_list) == 0:
        print("updated success,所有提交字段与返回值一致")
        return True
    else:
        print("error updating,校验不通过,错误详情:")
        for err in error_list:
            print(f"- {err}")
        return False

# 调用校验函数
check_status(post_data, response_data)

实现说明

  • 用字段映射表适配提交参数和返回值字段名不一致的场景,后续如果接口新增校验字段,直接在映射表中添加对应关系即可,不需要修改核心校验逻辑
  • 增加字段存在性判断,避免接口返回结构变化时触发KeyError导致脚本崩溃
  • 一次性收集所有校验错误,不会遇到第一个错误就终止校验,方便一次性排查所有问题
  • 函数最终返回布尔类型的校验结果,方便后续业务逻辑根据校验结果做分支处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:24:15