json - Django 没有发送正确的 json 响应

标签 json django http

我建立了一个简单的项目,当发出发布请求时,它会根据用户输入的值返回响应。

我正在 postman 中测试我的 api 逻辑。

目前,无论我输入什么值,都会发回相同的 json 响应。这不是预期的逻辑。

views.py:

def function(request):
    if request.method == 'POST':
        if request.POST.get("number") == 1:
            print("Number is 1")
            return JsonResponse({'message':'Number is 1'})
        else:
            print("Number is not 1")
            return JsonResponse({'message':'Number is not 1'})

即使 number 的值等于 1,也会返回消息:Number is not 1,。

postman 请求:

{
    "number": 1
}

谢谢。

最佳答案

来自docs :

If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.

由于您发送的数据是“非表单”数据,因此您需要改用 request.body:

import json

def function(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        if data.get("number", 0) == 1:
            print("Number is 1")
            return JsonResponse({'message':'Number is 1'})
        else:
            print("Number is not 1")
            return JsonResponse({'message':'Number is not 1'})

关于json - Django 没有发送正确的 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58253265/

相关文章:

Django 南 : How to create rules for a Custom Field?

http - 如何将 Istio Service Mesh 从 http 升级到 http2?

c# - 网站安全测试显示 Response.Redirect 容易受到攻击

python - 使用 Flask,如何修改所有输出的 Cache-Control header ?

javascript - 使用 JSON 初始化 JavaScript 对象

java - FLAT JSON ARRAY 到带有 Jackson JSON lib 的 Bean 列表

javascript - 如何在从根遍历到json树的目标 Node 时插入键?

java - 在 kotlin 中将 String 转换为 JsonObject 返回 null

javascript - 使用 Django-chartit 更改 Highcharts 标签和排序 x 轴

python - 为什么 Django 使用 db_constraint=False 为 ForeignKey 创建索引