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

如何查看Django测试客户端发送的请求体?

Django测试中查看PUT请求体的方法

Django自带的测试客户端返回的response.request字典里确实默认没有请求体相关的键,但你可以通过以下几种方式获取请求体内容:

  • 直接记录发送的payload
    发送请求前先把要提交的数据存为变量,之后直接打印查看即可,简单直接:

    payload = json.dumps({"key": "value"})
    # 注意补充缺失的右括号
    response = self.client.put(path, data=payload, content_type='application/json')
    print("请求体内容:", payload)
    
  • 通过WSGI环境捕获请求体
    利用Django的request_started信号,在请求发起时从WSGI环境中读取请求体:

    from django.core.signals import request_started
    from django.dispatch import receiver
    
    captured_body = None
    
    @receiver(request_started)
    def capture_body(sender, environ, **kwargs):
        global captured_body
        # 重置文件指针后读取内容
        environ['wsgi.input'].seek(0)
        captured_body = environ['wsgi.input'].read()
    
    class YourPutTest(TestCase):
        def test_put_endpoint(self):
            global captured_body
            captured_body = None
            payload = json.dumps({"key": "value"})
            response = self.client.put(path, data=payload, content_type='application/json')
            print("捕获到的请求体:", captured_body)
    

    必须指定content_type='application/json',否则Django会以表单格式解析数据,导致wsgi.input的内容被提前读取清空。

  • 使用DRF的APIClient(若项目用DRF)
    如果你用Django REST Framework,它的APIClient会在response.request里自动包含BODY键:

    from rest_framework.test import APIClient
    
    client = APIClient()
    response = client.put(path, {"key": "value"}, format='json')
    print(response.request['BODY'])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:42:02