官方文档:https://www.django-rest-framework.org/
中文文档:https://q1mi.github.io/Django-REST-framework-documentation/#django-rest-framework
Admin后台管理
后面笔记会详细介绍
- Django内置后台管理
- 自带User和Group
REST难点
模型序列化
正向序列化
- 将模型转换成JSON
反向序列化
- 将JSON转换成模型
Serialization类
HyperLinkedModelSerializer子类
- 序列化模型,并添加超级链接(带超级链接的模型序列化工具,常用语ORM开发中)
Serializer子类
- 手动序列化
Rest-Framework简介
Django REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:- The Web browsable API is a huge usability win for your developers.
- Authentication policies including packages for OAuth1a and OAuth2.
Serialization that supports both ORM and non-ORM data sources.
- 序列化支持基于ORM和不基于ORM
- Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
- Extensive documentation, and great community support.
Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
依赖环境
REST framework requires the following:
- Python (3.5, 3.6, 3.7, 3.8, 3.9)
- Django (2.2, 3.0, 3.1)
We highly recommend and only officially support the latest patch release of each Python and Django series.
The following packages are optional:
- PyYAML, uritemplate (5.1+, 3.0.0+) - Schema generation support.
- Markdown (3.0.0+) - Markdown support for the browsable API.
- Pygments (2.4.0+) - Add syntax highlighting to Markdown processing.
- django-filter (1.0.1+) - Filtering support.
- django-guardian (1.1.1+) - Object level permissions support.
实验
python命名规范
- 拒绝中文,空格,关键字,保留字,特殊字符在命名和路径中
- 拒绝数字开头,拒绝$开头
- 小写字母或者大写字母开头,驼峰或者蛇形命名
配置环境
使用
python manage.py startapp REST
创建App
接着在应用中新建urls.py
接着在settings.py中注册REST:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App.apps.AppConfig',
'REST',
]
在总urls.py中注册REST下的urls.py:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cbv/', include('App.urls', namespace='cbv')),
url(r'^rest/', include('REST.urls', namespace='rest')),
]
安装Djangorestframework
pip install --user djangorestframework
使用序列化器
定义一些序列化程序,用做数据表示
REST下新建serializers.py:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User # User是Django内置的,这里用来体验一下Framework序列化
fields = ('url','username','email','groups')
class GroupSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model= Group
fields = ('url','name')
在settings中注册restframework:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App.apps.AppConfig',
'REST',
'rest_framework',
]
Views
在views中创建类视图:
from django.contrib.auth.models import User, Group
from django.shortcuts import render
from rest_framework import viewsets
from REST.serializers import UserSerializer,GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class GropViewSet(viewsets.ModelViewSet):
queryset =Group.objects.all()
serializer_class = GroupSerializer
Urls
根据官网的文档,我们不用以前的形式,而是写成如下形式:
from rest_framework.routers import DefaultRouter
from REST.views import UserViewSet, GroupViewSet
router = DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
接着我们要在总urls.py中注册刚刚的urls文件:
总urls:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'cbv/', include('App.urls', namespace='cbv')),
path(r'rest/', include(router.urls)),
]
注意
- 这里要换成django2.0版本以上,所以所有的路由匹配url要改成path,并且不需要添加任何的正则符号
- 在总urls注册时,namespace不能使用
rest
来命名。
测试
可以看到这里将刚刚的两个路由全部列出,点击进入users路由查看详情:
可以看到restframework提供了可视化的api请求操作,并且支持get,post,head,options请求。
并且还支持不同的数据类型:
使用postman来调用restframework提供的接口
用postman来get刚刚创建的接口
我们也可以使用postman 中的post请求或者其他请求。
总结
- 代替之前我们手动创建restful格式的接口,自动实现增删改查的功能
- 提供序列化器
视图函数
- 继承viewsets.ModelViewSet
- 采用CBV
- 本身是一个视图集合
路由
- 采用router.DefaultRouter
- 需要在INSTALLED_APPS添加rest_framework
启用rest_framework运行之后
- 所有api变成可视化
超链接
- 使用了HyperLinkedModelSerializer
对数据集合实现了
- 路由访问就是访问urls中创建的router中的,users、groups
- get
- post
对单个数据实现了
- 路由访问就是访问/users/id/, /groups/id/
- get
- post
- put
- delete
- patch
- ViewSets起到了视图函数的实现
- Router做了数据集合路由以及其后面的单个数据id的路由注册
此处评论已关闭