Django-rest framework框架的安装配置和简介、Restful接口规范、基于原生django书写满足restful规范的接口 (2)

项目名下的urls.py

from django.conf.urls import url, include from django.contrib import admin from api import views urlpatterns = [ url(r\'^admin/\', admin.site.urls), url(r\'^test/\', views.Test.as_view()), # 路由分发 url(r\'^api/\', include(\'api.urls\')), ]

app名下的urls.py:api\urls.py

from django.conf.urls import url from . import views urlpatterns = [ url(r\'^books/$\', views.Book.as_view()), # 群查 url(r\'^books/(?P<pk>\d+)/$\', views.Book.as_view()), # 单查 ]

上面两个url都对应视图函数文件内的视图类Book

view.py

from django.http import JsonResponse from django.views import View from . import models from rest_framework.views import APIView class Book(View): def get(self, request, *args, **kwargs): pk = kwargs.get(\'pk\', None) if pk: # 单查 book_dic = models.Book.objects.filter(pk=pk).values(\'name\', \'price\').first() results = book_dic else: # 群查 book_query = models.Book.objects.values(\'name\', \'price\') results = list(book_query) if not results: return JsonResponse({ \'status\': 1, \'msg\': \'data error\', }) return JsonResponse({ \'status\': 0, \'msg\': \'ok\', \'results\': results }) CBV请求生命周期

as_view()方法完成路由匹配 => url请求会调用as_view()的返回值视图函数view => 调用dispatch()方法完成请求分发 => 视图类的具体视图方法处理请求 => 返回给前台

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwxjzy.html