python Django API 接口实现(基本流程及步骤)

1、安装插件,django拥有restful插件:pip   install   djangorestframework、django-filter、Markdown

2、配置settings

python Django API 接口实现(基本流程及步骤)_第1张图片

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES':[
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
    'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE':3  (可先注释,加页码会用到)
}

python Django API 接口实现(基本流程及步骤)_第2张图片

3、使用接口需要有数据库模型

①在路由当中注册接口:

from rest_framework import routers
from Store.views import *


router = routers.DefaultRouter() #声明一个默认的路由注册器
router.register(r'goods',UserViewSet)#注册写好的接口视图
router.register(r'goodsType',TypeViewSet)#注册写好的接口视图

urlpatterns = [
    re_path(r'^API',include(router.urls)),] #restful 根路由

python Django API 接口实现(基本流程及步骤)_第3张图片

②项目下创建serializers.py文件,存放接口过滤器:

from rest_framework import serializers
from Store.models import *

class UserSerializer(serializers.HyperlinkedModelSerializer):
    # 声明数据
    class Meta:
        model = Goods #要进行接口序列化的模型
        fields = ['goods_name','goods_price','goods_number','id','goods_date','goods_safeDate']#序列要返回的字段


class GoodsTypeSerializer(serializers.HyperlinkedModelSerializer):
    # 声明查询的表和返回的字段
    class Meta:
        model = GoodsType
        fields = ['name','description']

③在视图当中查询接口要返回的数据,并制定过滤器:

from rest_framework import viewsets
from Store.serializers import *

class UserViewSet(viewsets.ModelViewSet):

    queryset = Goods.objects.all()#具体返回的数据
    print(queryset)
    serializer_class = UserSerializer#指定过滤的类



class TypeViewSet(viewsets.ModelViewSet):
    # 返回具体查询的内容
    queryset = GoodsType.objects.all()
    serializer_class = GoodsTypeSerializer

python Django API 接口实现(基本流程及步骤)_第4张图片

4、在web端使用接口,通常要用到ajax和vue,首先导入vue和vue-resource数据通过接口返回,然后前端使用ajax进行请求,使用vue进行渲染。

Vue.use(VueResource);
var vue = new Vue(
    {
        el: "#goods",
        data: {
            goods_list: []
        },
        created:function () {
            this.$http.get("/APIgoods/").then(
                function (data) {
                    this.goods_list = data.data;
                    console.log(data.data)
                },
                function (error) {
                    console.log(error)
                }
            )
        },
        methods: {

        }
    }
);

python Django API 接口实现(基本流程及步骤)_第5张图片

5、接口的分页配置

python Django API 接口实现(基本流程及步骤)_第6张图片

    Vue.use(VueResource); //使用vueresource对象
    var vue = new Vue(
        {
            el: "#goods", //指定绑定的范围对象
            data: {
                goods_list: [],
                page_range: []
            }, //具体绑定的数据对象
            created:function () {
                this.$http.get("/APIgoods/").then( //发起ajax get请求
                    function (data) {
                        this.goods_list = data.data.results; //将接受的数据绑定到vue对象上
                        page_number = Math.ceil(data.data.count/10);
                        var page_range = [...new Array(page_number).keys()];
                        this.page_range = page_range //将接受的数据绑定到vue对象上
                    }, //如果请求成功执行的函数
                    function (error) {
                        console.log(error)
                    }
                )
            }, //初始化方法
            methods: {
                get_page_data:function (page) {
                    this.$http.get("/APIgoods/?page="+page).then(
                    function (data) {
                        this.goods_list = data.data.results;
                        page_number = Math.ceil(data.data.count/10);
                        var page_range = [...new Array(page_number).keys()];
                        this.page_range = page_range
                    },
                    function (error) {
                        console.log(error)
                    }
                )
                } //可以被v-on绑定的方法
            }
        }
    );
script>

 

你可能感兴趣的:(python Django API 接口实现(基本流程及步骤))