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

MicroPython向Django发送POST请求时Payload为空问题排查

MicroPython POST请求到Django时Payload为空的问题解决

你遇到的问题核心在于MicroPython的urequests库与CPython的requests库对请求参数的处理逻辑不同,以及请求头与数据格式不匹配,具体原因和解决方法如下:

问题分析

  1. 第一个版本代码问题:
    CPython的requests库会自动将字典格式的data参数编码为application/x-www-form-urlencoded格式的字符串,但MicroPython的urequests库不具备这个自动编码能力。直接传字典给data会导致实际发送的请求数据格式不符合Django对表单数据的解析要求,因此Django接收不到有效值。

  2. 第二个版本代码问题:
    你将字典转成了JSON字符串,但请求头仍然设置为application/x-www-form-urlencoded,这导致Django误以为接收的是表单数据,而实际上是JSON格式,自然无法解析出正确的参数值。

解决方案

方案1:以表单格式发送请求(适配Django默认的表单解析)

手动将字典编码为x-www-form-urlencoded格式的字符串,同时保持对应的请求头:

import urequests as requests
import urllib.parse as urlparse  # MicroPython部分环境需使用u urllib.parse

url = "http://192.168.0.33:8000/species/"

payload = {
    'name': 'test12',
    'classification': 'sheep12',
    'language': 'sheep_lang12'
}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

# 手动编码表单数据
encoded_data = urlparse.urlencode(payload)
response = requests.post(url, headers=headers, data=encoded_data)

print('success')
print(response.text)

方案2:以JSON格式发送请求(需Django端适配解析)

修改请求头为application/json,同时传递JSON字符串格式的data:

import urequests as requests
import ujson as json

url = "http://192.168.0.33:8000/species/"

payload = {
    'name': 'test12',
    'classification': 'sheep12',
    'language': 'sheep_lang12'
}
headers = {'Content-Type': 'application/json'}

response = requests.post(url, headers=headers, data=json.dumps(payload))

print('success')
print(response.text)

Django端适配JSON解析(方案2需要)

Django默认不会自动解析JSON格式的请求体,需在视图中手动处理:

import json
from django.http import JsonResponse

def species_view(request):
    if request.method == 'POST':
        if request.content_type == 'application/json':
            # 解析JSON请求体
            data = json.loads(request.body)
            return JsonResponse({
                'name': data.get('name', ''),
                'classification': data.get('classification', ''),
                'language': data.get('language', '')
            })
        # 保留表单格式的解析逻辑
        return JsonResponse({
            'name': request.POST.get('name', ''),
            'classification': request.POST.get('classification', ''),
            'language': request.POST.get('language', '')
        })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:03:36