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

Python调用API时如何将phases字典正确嵌套传入data字典?

解决方案:嵌套字典传参调用API格式错误问题

问题根因

  • 调用requests.post时使用data参数传递数据,默认会以application/x-www-form-urlencoded格式编码请求体,这种格式不支持嵌套JSON结构,后台无法正确解析嵌套的phases字段
  • 接口要求phases是数组格式(对应Python的列表),你当前直接赋值的是单个字典,格式不匹配
  • 其余字段也存在类型不匹配的隐患:接口要求precedents为数组、users为数组、category为数字类型,你当前传的都是字符串或单个值

修正后代码

def create_flow_and_phases(request):

    phases = {
        "name": 'phase name',
        "description": 'phase description',
        "sequence_number": 1,
        "precedents": [] # 对齐接口要求改为空数组
    }


    data = {
        "name": request.POST['new_flow_name'],
        "description": request.POST['flow_description'],
        "category": int(request.POST['select_category']), # 转换为数字类型匹配接口要求
        "precedents": [], # 对齐接口要求使用数组,有对应值时填入数字数组即可
        "users": [request.session['user_pk']], # 转换为数组格式
        "phases": [phases] # 将单个字典套入列表,匹配接口的数组要求
    }

    # 发起POST请求保存流程和阶段
    url = API_HOST + "/api/flows/save_flow_and_phases/"

    # 使用json参数代替data参数,requests会自动将请求头Content-Type设为application/json,按JSON格式序列化请求体
    answer = requests.post(url, json=data, headers={'Authorization': 'Token ' + request.session['user_token']})

    if not answer.ok:
        raise Exception("An error occurred while creating flow.")

如果需要传入多个阶段,直接往phases对应的列表中添加对应字典即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:54:03