zoukankan      html  css  js  c++  java
  • django rest_framework--入门教程2

    接上文 这里先写一个GET请求的

    1.先在VIEW里定义一个方法 代码如下:

      

    @api_view(['GET', 'POST'])
    def book_request(request):
        if request.method == 'GET':
    	queryset = Book.objects.all()
        	serializer_class = BookSerializer
    	serializer = BookSerializer(queryset)
    	return Response(serializer.data, status=status.HTTP_201_CREATED)
        else: 
    	return Response({'key': 'value'}, status=status.HTTP_200_OK)
    

     这里的BookSerializer是上文定义的,注意

    serializer = BookSerializer(queryset)

    return Response(serializer.data, status=status.HTTP_201_CREATED)

    此处2行与上一篇文不一样,这里如果没有返回会提示

    Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<type 'NoneType'>`

    2.url里加上路由规则

      url(r'^test/',include('quickstart.urls')),

      quickstart.urls:

      

    from django.conf.urls import *
    from rest_framework.views import *
    urlpatterns = patterns('quickstart.views',
        url(r'^$', 'book_request')
    )
    

     3.启动

      http://localhost:8000/test/

      提示错误:'QuerySet' object has no attribute 'id'

      但是序列化里已经有了这个字段了,后来想起官网API里序列化这一节有写,果然如果处理的是集合那么应该为

      serializer = BookSerializer(queryset,many=True)

      这个时候就可以正常了。

    其实我看这个rest_framwwork 只是为机器学习相关内容做铺垫,所以只是略微实现,如果要用请自行补充,博文只记录易错点。

     

  • 相关阅读:
    mysql资料
    MySQL启动与关闭
    poj 2778 DNA Sequence
    poj 1625 Censored!
    zoj 3228 Searching the String
    hdu 4605 Magic Ball Game
    hdu 4610 Cards
    SGU 439 A Secret Book
    NOI2013
    NOI2014
  • 原文地址:https://www.cnblogs.com/EncryptingLife/p/5150060.html
Copyright © 2011-2022 走看看