【问题标题】:POST JSON request data dropped/disappear when sending to djangorestframework发送到 djangorestframework 时,POST JSON 请求数据丢失/消失
【发布时间】:2016-06-30 07:44:04
【问题描述】:

我一直坚持使用 django-rest-framework 进行简单的 RESTful 测试。我是新手。请帮忙。提前致谢!

版本:

django >= 1.9

djangorestframework 3.3.3

python 3.4.3

来自终端的 POST 请求

curl -H "Content-Type: application/json" -X POST -d '{"title":"xyz","desc":"xyz"}' http://localhost:3000/api/test/

django 的 settings.py

INSTALLED_APP = {
   'app',
   'rest_framework',
   #....skip to keep it short
}

# did not set anything

<!-- language-all: lang-python -->
REST_FRAMEWORK = {
}

#models.py

class Test(object):
    def __init__(self, title, desc):
        self.title = title
        self.desc = desc

serializers.py

from rest_framework import serializers

class TestSerializer(serializers.Serializer):
    title = serializers.CharField()
    desc = serializers.CharField(max_length=200)
    class Meta:
        model = Test
        fields = ('title', 'desc')

views.py

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
class TestView(APIView):

    def get(self, request, format=None):        
        # 1. we use NoSQL, is the following line still work?
        # testItems = Test.objects.all()
        serializer = SnippetSerializer(testItems, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        # 2. Unable to get any json string in request object or request.data at all!
        # 3. The entire json seems disappear and get dropped
        serializer = TestSerializer(data=request.data)
        if serializer.is_valid():
            # 4. can save() be overrided and do custom implementation? How?
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

from django.conf.urls import patterns, url

urlpatterns = patterns(
    'app',
    url(r'^api/business/$', app.views.TestView.as_view()),
)

我的问题:

  1. 我们使用 NoSQL,以下行是否仍然有效?
  2. testItems = Test.objects.all()
  3. POST JSON 请求中的 request.data 为空。
  4. 无法获取请求对象中的任何 json 字符串 或 request.data !整个 json 似乎消失并得到 掉了。尝试使用 Fiddler/Postman 捕获并确保确实发送了 JSON
  5. 能否覆盖 save() 并进行自定义实现?怎么样?

【问题讨论】:

    标签: python json django curl django-rest-framework


    【解决方案1】:

    我不知道 NOSQL 但你可以在 shell 上测试它。我猜它可能有效。 关于request.data错误; request.data 仅用于 django rest 框架的文件上传。当您发布 json 时,它位于请求的正文中。在您看来,您应该做的是这样的事情:

    from django.views.decorators.csrf import csrf_exempt
    from django.http import HttpResponse
    import json
    
    @csrf_exempt
    class TestView(APIView):
    
    # your get request here.
    
        def post(self, request, format=None):
            body_unicode = request.body.decode('utf-8')
            data = json.loads(body_unicode)
            # Now, your json content is stores in data as a dictionary.
            serializer = TestSerializer(data=request.data)
            if serializer.is_valid():
                # 4. can save() be overrided and do custom implementation? How?
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    

    仅供参考,我使用序列化程序来创建 json,我不使用它来创建对象。因此,我不确定这个版本 %100 是否有效。但我很确定我添加的 2 行将 JSON 转换为字典。如果序列化程序接受字典作为数据,它就会工作。

    【讨论】:

      猜你喜欢
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2020-04-06
      • 2020-09-23
      • 1970-01-01
      相关资源
      最近更新 更多