#django一个接口的开发简单逻辑举例:
1-建表,写入数据
2-接口逻辑,接口逻辑使用CBV,使用类的继承特性,把get方法公共部分写入custom_views,在views继承或重写公共方法,传入变量等,
3-优化接口:使用form对接口的传入的参数进行验证、重写JsonResponse,优化返回参数
4-配置urls(CBV方式),接口调用,
#具体代码
1- models.py
from django.db import models # Create your models here. class BaseModel(models.Model): is_delete_choice = ( (1,‘删除‘), (0,‘正常‘) ) is_delete = models.SmallIntegerField(choices=is_delete_choice,default=0,verbose_name=‘是否被删除‘) create_time = models.DateTimeField(verbose_name=‘创建时间‘,auto_now_add=True) updata_time = models.DateTimeField(verbose_name=‘修改时间‘,auto_now=True) class Meta: abstract = True #只是用来继承,不会创建这个表 class Parameter(BaseModel): name = models.CharField(max_length=200,verbose_name=‘参数名称‘,unique=True) desc = models.CharField(max_length=200,verbose_name=‘描述‘) value = models.CharField(max_length=200,verbose_name=‘参数值‘) def __str__(self): return self.name class Meta: verbose_name = ‘全局参数表‘ verbose_name_plural = verbose_name db_table = ‘parameter‘
2- views接口逻辑
custom_views.py
def model_to_dict(instance, fields=None, exclude=None): opts = instance._meta data = {} for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many): if fields and f.name not in fields: continue if exclude and f.name in exclude: continue value = f.value_from_object(instance) if isinstance(value, datetime.datetime): value = value.strftime(‘%Y-%m-%d %H:%M:%S‘) if isinstance(value, datetime.date): value = value.strftime(‘%Y-%m-%d‘) data[f.name] = value return data class BaseView(View): model_class = None form_class = None @property def model(self): if self.model_class and issubclass(self.model_class,Model): return self.model_class raise Exception("未定义model_class") @property def form(self): # issubclass 参数1 是不是 参数2的子类 if self.form_class and issubclass(self.form_class, BaseForm): return self.form_class raise Exception("未定义form_class") class GetView(BaseView): def get(self, request): # get请求时 获取传递过来的第几页数据 page = request.GET.get(‘page‘) limit = request.GET.get(‘limit‘) # filter_dict = self.get_filter_dict() # search_dict = self.get_search_dict() # search_q = self.get_search_dict_or() qs = self.model.objects.filter(is_delete=0) page_obj = Paginator(qs, limit) # page_obj Paginator实例对象 # 获取第几页的数据 page_data = page_obj.get_page(page) # 用于存储返回的dict类型数据 data_list = [] for data in page_data: # 通过model_to_dict 转换成dict tmp_data = model_to_dict(data) data_list.append(tmp_data) return NbResponse(data=data_list,count=page_obj.count) views.Py# Create your views here. from app9.custom_views import GetView from . import models class Parameter(GetView): model_class = models.Parameter form_class = forms.ParameterForm
3- 接口优化
使用form
from django.http import JsonResponse class NbResponse(JsonResponse): def __init__(self, code=0, msg=‘操作成功‘, **kwargs): data = {"code": code, "msg": msg} data.update(kwargs) super().__init__(data=data, json_dumps_params={"ensure_ascii": False})
优化response class ParameterForm(forms.ModelForm): class Meta: model = models.Parameter # 创建类变量和model建立映射关系 exclude = [‘id‘, ‘is_delete‘, ‘update_time‘, ‘create_time‘]
4-配置urls
子项目urls.py
from django.urls import path from . import views # from .views import Parameter urlpatterns = [ # cbv # path(‘c_parameter‘, Parameter.as_view()), # 优化代码路由 # path(‘s_parameter‘, SParameter.as_view()), path(‘parameter‘, views.Parameter.as_view()), ] 主项目urls.py应用子项目 from django.contrib import admin from django.urls import path,include from app9 import urls urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘api/‘, include(urls)), ]
原文:https://www.cnblogs.com/whcp855/p/13704685.html