Django之前学习的的都是实现前后的不分离式的,Django也可以实现前后端分离式的开发,即视图中不使用render返回渲染的html页面,而是改用JsonResponse返回json字符串
1.创建testcaset应用,并将'testcase.apps.TestcaseConfig',添加到settings.py的INSTALLED_APPS中
2.models.py ----------表结构设计
1 from django.db import models 2 3 # Create your models here. 4 class BaseModel(models.Model): 5 create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') 6 update_time = models.DateTimeField(auto_now=True, verbose_name='修改时间') 7 is_delete = models.BooleanField(verbose_name='是否删除', default=False) 8 9 class Meta: 10 abstract = True #声明这个类只是用来继承的,不会创建这张表 11 12 class CaseSet(BaseModel):#用例集合和用例多对多关系 13 name = models.CharField(verbose_name='集合名称',max_length=60) 14 desc = models.CharField(verbose_name='集合描述',max_length=70) 15 class Meta: 16 db_table = 'case_set' 17 verbose_name = '用例集合表' 18 verbose_name_plural = verbose_name 19 20 def __str__(self): 21 return self.name 22 23 class Case(BaseModel): 24 title = models.CharField(verbose_name='用例标题',max_length=80,db_index=True) 25 desc = models.CharField(verbose_name='用例描述',max_length=120) 26 method_choice = [ 27 [0,'get'], 28 [1,'post'], 29 [2,'put'], 30 [3,'delete'] 31 ] #枚举 32 method = models.SmallIntegerField(choices=method_choice,verbose_name='请求方式',default=0) 33 url = models.URLField(max_length=50,verbose_name='请求url') 34 params = models.TextField(verbose_name='请求参数') 35 run_count = models.IntegerField(verbose_name='运行次数',default=0) 36 run_time = models.DateTimeField(verbose_name='运行时间',default=None) 37 case_set = models.ManyToManyField(CaseSet,db_constraint=False,verbose_name='用例集合') 38 39 class Meta: 40 db_table = 'case' 41 verbose_name = '用例表' 42 verbose_name_plural = verbose_name 43 44 def __str__(self): 45 return self.title
3.views.py---------------------视图实现返回接口
1 from django.forms import model_to_dict 2 from django.http import JsonResponse 3 from django.shortcuts import render 4 from django.views import View 5 6 from . import models 7 8 9 # Create your views here. 10 # django前后端分离,开发后端接口 11 def case_set(request): 12 # 添加用例集合 13 name = request.POST.get('name') 14 desc = request.POST.get('desc') 15 if name.strip() and desc.strip(): 16 models.CaseSet.objects.create(name=name, desc=desc) 17 data = {'code': 0, 'msg': '添加成功'} 18 else: 19 data = {'code': -1, 'msg': '参数错误'} 20 return JsonResponse(data) # 通过JsonResponse类返回json字符串,data必须传字典,不然会报错 21 22 23 def case_set_all(req): 24 case_sets = models.CaseSet.objects.filter(is_delete=False) 25 data = [] 26 for c in case_sets: 27 d = model_to_dict(c) 28 data.append(d) 29 response = {'code': 0, 'msg': '添加成功', 'data': data} 30 return JsonResponse(response, json_dumps_params={'ensure_ascii': False}) # 汉字不转义 31 32 33 # restful代码设计风格,不同的请求方式整个在一个方法中,不需要定义多个方法 34 def case_set_new(req): 35 if req.method == 'GET': 36 case_sets = models.CaseSet.objects.filter(is_delete=False) 37 data = [] 38 for c in case_sets: 39 d = model_to_dict(c) 40 data.append(d) 41 response = {'code': 0, 'msg': '添加成功', 'data': data} 42 return JsonResponse(response, json_dumps_params={'ensure_ascii': False}) # 汉字不转义 43 elif req.method == 'POST': 44 name = req.POST.get('name') 45 desc = req.POST.get('desc') 46 if name.strip() and desc.strip(): 47 models.CaseSet.objects.create(name=name, desc=desc) 48 data = {'code': 0, 'msg': '添加成功'} 49 else: 50 data = {'code': -1, 'msg': '参数错误'} 51 return JsonResponse(data) # 通过JsonResponse类返回json字符串 52 elif req.method == 'PUT': 53 pass 54 elif req.method == 'DELETE': 55 pass 56 57 58 # cvb 59 class CaseSet(View): 60 def get(self): 61 case_sets = models.CaseSet.objects.filter(is_delete=False) 62 data = [] 63 for c in case_sets: 64 d = model_to_dict(c) 65 data.append(d) 66 response = {'code': 0, 'msg': '添加成功', 'data': data} 67 return JsonResponse(response, json_dumps_params={'ensure_ascii': False}) # 汉字不转义 68 69 def post(self, req): 70 name = req.POST.get('name') 71 desc = req.POST.get('desc') 72 if name.strip() and desc.strip(): 73 models.CaseSet.objects.create(name=name, desc=desc) 74 data = {'code': 0, 'msg': '添加成功'} 75 else: 76 data = {'code': -1, 'msg': '参数错误'} 77 return JsonResponse(data) # 通过JsonResponse类返回json字符串 78 79 def put(self, req): 80 pass 81 82 def delete(self, req): 83 pass
4.testcase/urls.py-----------配置urls
1 from django.urls import path 2 from . import views 3 4 urlpatterns = [ 5 path('add_case_set/',views.case_set), 6 path('case_set/',views.case_set_all), 7 path('case_set_new/',views.case_set_new) 8 ]
5.dj_test/urls.py-----------项目中配置url
1 from django.contrib import admin 2 from django.urls import path,include 3 from testcase import urls 4 5 urlpatterns = [ 6 #引用子应用中的url 7 path('testcase/',include(urls)) 8 ]
6.浏览器输入:http://127.0.0.1:8000/testcase/case_set_new 或者postman进行访问