page contents

API接口开发

最原始的接口搭建是使用类视图搭建接口,但接口的规范很难约束,接着就出现了接口框架。使用框架进行规范的接口开发即restful,django具有restful的插件(djangorestframework)。下面来具体实现开发一个接口。

image


前言

在工作中,逐渐多的出现不使用页面展示数据,直接使用数据接口,这样有以下好处:

1.首先可以实现动静分离,将数据库的查询和页面的渲染彻底分开。

2.网站可以支持批量的脚本开发。

最原始的接口搭建是使用类视图搭建接口,但接口的规范很难约束,接着就出现了接口框架。使用框架进行规范的接口开发即restful,django具有restful的插件(djangorestframework)。下面来具体实现开发一个接口。


接口开发步骤

1.安装插件

Pip install djangorestframework
Pip install django-filter
Pip install Markdown (restful依赖包)

attachments-2021-01-SgRdgZoj5ffe99b8d5550.png

2.配置settings

attachments-2021-01-rQZEd8OE5ffe99c285e3f.png

attachments-2021-01-zt8f224a5ffe99dba8626.png

注意:使用接口尽量需要有数据库模型

attachments-2021-01-RXMIdZip5ffe99e87cc59.png

3.编写接口逻辑

3.1创建序列化,在对应APP下创建serializers.py.(名称可任意,但是通常项目中会这样写)

1.  #当前文件只是为了规定接口模型和数据字段
    
2.  from django.contrib import admin
    
3.  from django.urls import path,include,re_path
    
4.  from Buyer.views import index
    
5.  from Store.models import Goods
    
6.  from Store.models import GoodsType
    

8.  from rest_framework import routers, serializers, viewsets
    
9.  #导入框架
    

11.  # Serializers define the API representation.
    
12.  classUserSerializer(serializers.HyperlinkedModelSerializer):
    
13.  """
    
14.  声明数据
    
15.  """
    
16.  classMeta: #元类
    
17.  model = Goods #要进行接口序列化的模型
    
18.  fields = ['goods_name', 'goods_price', 'goods_number', 'goods_description'] #序列要返回的字段
    

20.  classGoodsTypeSerializer(serializers.HyperlinkedModelSerializer):
    
21.  """
    
22.  声明查询的表和返回的字段
    
23.  """
    
24.  classMeta:
    
25.  model = GoodsType
    
26.  fields = ["name","description"]

3.2对应APP的views下:在这是通过url指向,所以更类似于视图

1.  from rest_framework import viewsets
    
2.  from Store.Serializers import *
    
3.  # ViewSets define the view behavior.
    
4.  #当前部分还是执行接口的查询逻辑
    
5.  classUserViewSet(viewsets.ModelViewSet):
    
6.      queryset = Goods.objects.all() #具体返回的数据
    
7.      serializer_class = UserSerializer #指定过滤的类
    
8.  classTypeViewSet(viewsets.ModelViewSet):
    
9.      """
    
10.   返回具体查询的内容
    
11.   """
    
12.      queryset = GoodsType.objects.all()#查询所有数据
    
13.      serializer_class = GoodsTypeSerializer#需要的数据需要从这里找
    

3.3 url指出接口

1.  from Store.views import UserViewSet
    
2.  from Store.views import TypeViewSet
    
3.  from rest_framework import routers
    
4.  router = routers.DefaultRouter() #声明一个默认的路由注册器
    
5.  router.register(r"goods",UserViewSet) #注册写好的接口视图
    
6.  router.register(r"goodsType",TypeViewSet) #注册写好的接口视图
    

9.  urlpatterns = [
    
10.      path('admin/', admin.site.urls),
    
11.      path('Store/', include("Store.urls")),
    
12.      path('Buyer/', include('Buyer.urls')),
    
13.      path('ckeditor/',include('ckeditor_uploader.urls')),
    
14.      re_path('^API', include(router.urls)), #restful 的根路由
    
15.      re_path('^api-auth',include('rest_framework.urls')) #接口认真
    
16.  ]
    


按照功能对项目进行划分:

1.创建serializers文件用来存放接口的过滤器。

attachments-2021-01-TmFK4Rwm5ffe99fd22662.png

2.在视图当中查询接口要返回的数据,并指定过滤器。(views)

attachments-2021-01-gsnpA1qS5ffe9a0898410.png

3.在路由中注册接口.

attachments-2021-01-j2pIVNQe5ffe9a11dc697.png


web端使用接口

通常要用到ajax和vue,数据通过接口返回,然后前端使用ajax进行请求,使用vue进行渲染

1.准备静态页面

2.编写视图

attachments-2021-01-cENUSOA95ffe9a1d2e907.png

3.路由指出

attachments-2021-01-wnEGVyEC5ffe9a248256f.png

4.静态页面ajax访问接口

1.  Vue.use(VueResource);#此处的Vue是使用VueResource中的Vue.
    
2.  var vue = new Vue(
    
3.      {
    
4.          el: "#goods",
    
5.          data: {
    
6.              goods_list: []
    
7.          },
    
8.          created:function () {
    
9.              this.$http.get("/APIgoods/").then(
    
10.                  function (data) {
    
11.                      this.goods_list = data.data;
    
12.                      console.log(data.data)
    
13.                  },
    
14.                  function (error) {
    
15.                      console.log(error)
    
16.                  }
    
17.              )
    
18.          },
    
19.          methods: {
    

21.          }
    
22.      }
    
23.  );
    


image

来源:https://blog.csdn.net/weixin_44689393/article/details/100750360

  • 发表于 2021-01-13 14:56
  • 阅读 ( 661 )

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Pack
Pack

1135 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1320 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章