django中的restful规范
基于django的原生restful规范
主路由:url.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
# 路由分发
url(r'^api/', include('api.urls'))
]
api组件的子路由:api/url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^books/', views.Book.as_view()),
url(r'^books/(?P<pk>.*)/$', views.Book.as_view()),
]
模型层:model.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name
def __str__(self):
return '《%s》' % self.title
后台层:admin.py
from django.contrib import admin
from . import models
admin.site.register(models.Book)
数据库迁移
python manage.py makemigrations
python manage.py migrrate
python manage.py createsuperuser # 创建管理员
视图层:views.py
from django.http import JsonResponse
from django.views import View
from . import models
# 六大基础接口:获取一个 获取所有 增加一个 删除一个 整体更新一个 局部更新一个
class Book(View):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if not pk: # 群查
# 操作数据库
book_obj_list = models.Book.objects.all()
# 序列化过程
book_list = []
for obj in book_obj_list:
dic = {}
dic['title'] = obj.title
dic['price'] = obj.price
book_list.append(dic)
# 响应数据
return JsonResponse({
'status': 0,
'msg': 'ok',
'results': book_list
}, json_dumps_params={'ensure_ascii': False})
else: # 单查
book_dic = models.Book.objects.filter(pk=pk).values('title', 'price').first()
if book_dic:
return JsonResponse({
'status': 0,
'msg': 'ok',
'results': book_dic
}, json_dumps_params={'ensure_ascii': False})
return JsonResponse({
'status': 2,
'msg': '无结果',
}, json_dumps_params={'ensure_ascii': False})
# postman可以完成不同方式的请求:get | post | put ...
# postman发送数据包有三种方式:form-data | urlencoding | json
# 原生django对urlencoding方式数据兼容最好
def post(self, request, *args, **kwargs):
# 前台通过urlencoding方式提交数据
try:
book_obj = models.Book.objects.create(**request.POST.dict())
if book_obj:
return JsonResponse({
'status': 0,
'msg': 'ok',
'results': {'title': book_obj.title, 'price': book_obj.price}
}, json_dumps_params={'ensure_ascii': False})
except:
return JsonResponse({
'status': 1,
'msg': '参数有误',
}, json_dumps_params={'ensure_ascii': False})
return JsonResponse({
'status': 2,
'msg': '新增失败',
}, json_dumps_params={'ensure_ascii': False})
DRF简介
DRF从本质上来讲, 它就是一个Django的App, 有了这样一个App, 我们就可以更好的设计出符合RESTful规范的web应用. 虽然实际上, 即便没有DRF, 我们也能够自行设计出符合RESTful规范的web应用, 就如上面的例子所示.
DRF安装
pip3 install djangorestframework
DRF框架规矩的封装风格
from rest_framework.views import APIView # 基础的View视图
from rest_framework.response import Response # 基础的响应
from rest_framework.request import Request # 请求组件
from rest_framework.serializers import Serializer # 序列化模块
from rest_framework.settings import APISettings # 默认配置文件
from rest_framework.filters import SearchFilter # 过滤组件
from rest_framework.pagination import PageNumberPagination # 分页器组件
from rest_framework.authentication import TokenAuthentication # 认证组件
from rest_framework.permissions import IsAuthenticated # 权限组件
from rest_framework.throttling import SimpleRateThrottle # 频率组件
class Test(APIView):
def get(self, request, *args, **kwargs):
return Response('drf get ok')
DRF请求生命周期
"""
1) 请求走的是APIView的as_view函数
2) 在APIView的as_view调用父类(django原生)的as_view,还禁用了 csrf 认证
3) 在父类的as_view中dispatch方法请求走的又是APIView的dispatch
4) 完成任务方法交给视图类的请求函数处理,得到请求的响应结果,返回给前台
"""