Drango之 drf(drango restful framework)--------------第一天

一.CBV源码分析

          1 在views中写一个类,继承View,里面写get方法,post方法
          2 在路由中配置: url(r'^test/', views.Test.as_view()),实际上第二个参数位置,放的还是一个函数内存地址
          3 当请求来了,就会执行第二个参数(request,参数),本质上执行view()
          4 view内部调用了dispatch()方法
          5 dispatch分发方法,根据请求方式不同,执行的方法不同

 

二.resful规范

           -面向资源架构,面向资源编程
           -10个规范

            -与后台做交互,通常使用https
            -域名:
                -https://api.baidu.com(存在跨域问题)
                -https://www.baidu.com/api/
            -版本
                -https://www.baidu.com/api/v1
                -https://www.baidu.com/api/v2
            -路径,视网络上任何东西都是资源,均使用名词表示(可复数)
                -https://api.example.com/v1/books
                不是:https://api.example.com/v1/delete_one_book
            -method来表示增删查改
                -https://api.example.com/v1/books  get请求,获取所有书
                -https://api.example.com/v1/books  post请求,新增一本书
                -https://api.example.com/v1/book/1  delete请求,删除一本书
                -https://api.example.com/v1/book/1  get请求,获取id为1的这本书
                -https://api.example.com/v1/book/1  put/patch请求,修改id为1的这本书
                
            -过滤,通过在url上传参的形式传递搜索条件
                -https://api.example.com/v1/books?limit=10:只拿前10本
                -https://api.example.com/v1/books?price=10:只拿价格为10的书
            -状态码
                -{status:100,}
            -错误处理,应返回错误信息,error当做key
                {
                status:101,
                errors:'您没有权限操作这个事'
                }
            -返回结果,针对不同操作,服务器向用户返回的结果应该符合以下规范
                GET /collection:返回资源对象的列表(数组)
                GET /collection/resource:返回单个资源对象
                POST /collection:返回新生成的资源对象
                PUT /collection/resource:返回完整的资源对象
                PATCH /collection/resource:返回完整的资源对象
                DELETE /collection/resource:返回一个空文档
            -返回结果中提供链接(获取一本书)
                {
                    id:1
                    name:lxx
                    price:12
                    publish:www.xx.com/api/v1/publish/1
                }

三.django中写resful的接口

views.py:

from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
# Create your views here.
from django.views import View


class Test(View):
    def dispatch(self, request, *args, **kwargs):
        # 写代码
        obj = super().dispatch(request, *args, **kwargs)
        # 写代码
        return obj

    def get(self, request, *args, **kwargs):
        return HttpResponse('cbv_get')

    def post(self, request, *args, **kwargs):
        return HttpResponse('cbv_post')


user_list = [{'id': 1, 'name': 'lqz', 'age': 18}, {'id': 2, 'name': 'egon', 'age': 17},
             {'id': 3, 'name': 'xiaohou', 'age': 16}]


def users(request):
    response = {'status': 100, 'errors': None}
    if request.method == 'GET':
        response['users'] = user_list
        return JsonResponse(response, safe=False)
    if request.method == 'POST':
        name = request.POST.get('name')
        age = request.POST.get('age')
        user_list.append({'id': len(user_list) + 1, 'name': name, 'age': age})
        # response['user'] = {'id':len(user_list),'name': name, 'age': age}
        response['msg'] = '新增成功'
        return JsonResponse(response)


def user(request, id):
    response = {'status': 100, 'errors': None}
    if request.method == 'GET':
        id = int(id)
        response['user'] = user_list[id]
        return JsonResponse(response)

url.py:

     url(r'^test/', views.Test.as_view()),
     url(r'^users/', views.users),
     url(r'^user/(?P<id>\d+)', views.user),

前端渲染用postman

四.drf写resful的接口

       -先安装
             pip3 install djangorestframework
       -简单使用
           views.py:



from rest_framework.views import APIView
from rest_framework.response import Response


#
基于drf写接口,写cbv class DrfTest(APIView): def get(self, request, *args, **kwargs): # request是封装之后的request了,原来的request是request._request print(type(request._request)) print(type(request)) # 问:当前request对象并没有这些属性,但是能打印出来,为什么? # getattr print(request.method) print(request.POST) print(request.GET) # 就相当于: print(request.query_params) print(request._request.GET) response = {'status': 100, 'errors': None} response['users'] = user_list # 用drf的Response,可以通过请求客户端来判断返回数据格式是什么样的 return Response(response) # return JsonResponse(response) def post(self, request, *args, **kwargs): # post 提交的数据,urlencode,formdate,json格式,都能从data中取出来 name = request.data.get('name') # request.FILES print(name) return HttpResponse('ok')

      url.py:

  url(r'^users/', views.DrfTest.as_view()),

五.APIVIew源码分析

 

      dispatch方法:
     # 传入的request是原生的request对象
     # 这个request已经不是原生的request了,但是它内部有个原生的request对象
        request = self.initialize_request(request, *args, **kwargs)
        self.initial(request, *args, **kwargs)#这里面有权限,认证,频率

六.drf之序列化:  把python中的对象,转成json格式字符串

         url.py:

 

    url(r'^books/', views.Books.as_view()),
    url(r'^book/(?P<id>\d+)', views.Book.as_view()),

         myser.py:

from rest_framework import serializers


# from rest_framework.request import Request
class BookSerializer(serializers.Serializer):
    id = serializers.CharField()
    # 通过source可以改名
    name = serializers.CharField(source='title')
    price = serializers.CharField()

    xxx = serializers.CharField(source='test')
    # 1 变量名和source指定的值不能一样
    # 2 source='publish.name'还支持继续 .
    # 3 source 还支持方法(没用)
    # publish_name = serializers.CharField(source='publish.name')
    # publish_id = serializers.CharField(source='publish.pk')
    # 4 支持写方法,如下
        #方法一定传一个参数,是当前book对象
    publish_dic=serializers.SerializerMethodField()
    def get_publish_dic(self,obj):
        # 猜,这个obj应该是谁,当前book对象
        return {'id':obj.publish.pk,'name':obj.publish.name}

            views.py:

from app01 import models
from app01.MySer import BookSerializer


# 写一个获取所有图书的接口
class Books(APIView):
    def get(self, request, *args, **kwargs):
        response = {'status': 100, 'msg': '成功'}
        book_list = models.Book.objects.all()
        # 第一个参数是要序列化的queryset对象,如果序列化多条,必须指定many=True
        # 问?什么情况下many=False,instance=单个对象的时候
        book_ser = BookSerializer(book_list, many=True)
        print(book_ser.data)
        response['books'] = book_ser.data
        return Response(response)


class Book(APIView):
    def get(self, request, id):
        response = {'status': 100, 'msg': '成功'}
        book = models.Book.objects.filter(pk=id).first()
        book_ser = BookSerializer(book, many=False)
        response['book'] = book_ser.data
        return Response(response)

models.py:

from django.db import models

# Create your models here.
from django.db import models


# Create your models here.

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.IntegerField()
    pub_date = models.DateField()
    publish = models.ForeignKey("Publish")
    authors = models.ManyToManyField("Author")

    def test(self):
        return self.title + str(self.price)

    def __str__(self):
        return self.title


class Publish(models.Model):
    name = models.CharField(max_length=32)
    email = models.EmailField()

    # def __str__(self):
    #     return self.name
    # return str(self.pk)


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    #
    # def __str__(self):
    #     return self.name

七. 在线格式化json

-https://www.json.cn/


作业:
-研究一下什么是跨域
-图书的增删查该resful的接口写完,查的时候,返回所有的作者详情

 

posted @ 2019-08-20 00:07  纵横捭阖行  阅读(244)  评论(0编辑  收藏  举报