如何查看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
相关产品推荐
相关产品推荐

