通过 requests.post() 将字典传递给 API 的问题

Posted

技术标签:

【中文标题】通过 requests.post() 将字典传递给 API 的问题【英文标题】:Problem passing dictionary to API via requests.post() 【发布时间】:2022-01-06 18:32:23 【问题描述】:

如下所述,我正在尝试将字典 数据 传递给 API。

def create_flow_and_phases(request):

    data = 
        "name": "name_example",
        "description":"description_example",
        "category": 2,
        "precedents": [2,3],
        "users": [1],
        "phases": [
                "name": "phase_name",
                "description": "description name",
                "sequence_number": 1,
                "precedents": [1]
            ]
    

    # Making a POST request to save flow_and_phases
    url = API_HOST + "/api/flows/save_flow_and_phases/"

    answer = requests.post(url, data=data, headers='Authorization': 'Token ' + request.session['user_token'])

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

在下面,您可以看到字典 data 格式与 Insomnia 中传递给 API 的格式相同,并且可以完美运行。


  "name": "Testando criação de fluxo pelo Insomnia",
  "description": "Fluxo teste simulando informações de trato e colheita de café na fazendo fictícia Quipo",
  "category": 2,
  "precedents": [2, 3],
    "users": [1],
    "phases": [
         
            "name": "Trato anual",
            "description": "Descrição teste fase 1.",
            "sequence_number": 1,
            "precedents": []
         ,
        
            "name": "Trato anual 2",
            "description": "Descrição teste fase 2.",
            "sequence_number": 2,
            "precedents": [1]
         
    ]

后端接收数据如下

flow_data = dict(data) # data is passed as parameter

但是当我去运行debub时,引用阶段的数据并没有传递给API,如下面的截图所示

如图所示,没有通过阶段列表。发生了什么?有什么建议吗?

【问题讨论】:

【参考方案1】:

将数据发布为 JSON,嵌套数据不能作为常规 POST 数据。您可以在json 参数中传递数据,请求应为您处理标头和序列化

answer = requests.post(url, json=data, headers='Authorization': 'Token ' + request.session['user_token'])

【讨论】:

以上是关于通过 requests.post() 将字典传递给 API 的问题的主要内容,如果未能解决你的问题,请参考以下文章

将字典传递给 FxCop GUI

Python最小化函数:将附加参数传递给约束字典

将字典传递给控制器​​ asp.net mvc

将列表字典传递给 Qtablewidget - PyQT5

iOS Swift 如何从 UIWebView 将 JSON 字符串和数组或字典传递给 Javascript?

将字典作为关键字参数传递给函数