Django REST Framework简单入门(一)

Django REST Framework(简称DRF),是一个用于构建Web API的强大且灵活的工具包。

REST这个词,是Roy Thomas Fielding在他2000年的博士论文中提出的。

简单来说,RESTful架构:

(1)每一个URI代表一种资源;

(2)客户端和服务器之间,传递这种资源的某种表现层;

 (3)客户端通过四个HTTP动词(GET、POST、PUT、DELETE),对服务器端资源进行操作,实现"表现层状态转化"。

理解restful:RESTful API 设计指南理解RESTful架构

安装配置相关

1、安装

pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support

可选安装:

  • coreapi(1.32.0+) – 支持模式生成。
  • Markdown(2.1.0+) – Markdown支持可浏览的API。
  • django-filter(1.0.1+) – 过滤支持。
  • django-crispy-forms – 改进的HTML显示过滤。
  • django-guardian(1.1.1+) – 支持对象级别的权限控制。

2、注册到app

INSTALLED_APPS = (
...
'rest_framework',
)

3、配置可视化api

urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls'))
]

4、简单应用

1、先创建一个模型

class Role(models.Model):
"""
角色表
"""
title = models.CharField(max_length=32, verbose_name="角色名称") class Meta:
verbose_name = "角色表"
verbose_name_plural = "角色表" def __str__(self):
return self.title class User(models.Model):
"""
用户表
"""
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=32, verbose_name="用户名")
password = models.CharField(max_length=128, verbose_name="密码")
email = models.CharField(max_length=32, verbose_name="邮箱")
roles = models.ManyToManyField(to="Role", blank=True, verbose_name="用户关联的角色") class Meta:
verbose_name = "用户表"
verbose_name_plural = "用户表" def __str__(self):
return self.username

2、Serializers(序列化器)

序列化数据,在models.py 同级目录下新建一个serializers.py

from rest_framework import serializers

# HyperlinkedModelSerializer 会自动生成一个 url 字段来表示超链接
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'roles')
#fields = “all”
class RoleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Role
fields = ('title', 'permissions')

3、Views

开始写视图函数

ViewSets是一个视图集,就是把所有常见的行为组合在一起,而不是编写多个视图。如果需要的话,我们可以很容易地将这些视图分解成单独的视图,但是使用视图集使视图逻辑很好地组织,并且非常简洁。

from rest_framework import viewsets
from .serializers import UserSerializer,RoleSerializer class UserViewSet(viewsets.ModelViewSet):
"""
允许用户查看或编辑的API路径。
"""
queryset = User.objects.all()
serializer_class = UserSerializer class RoleViewSet(viewsets.ModelViewSet):
"""
允许角色查看或编辑的API路径。
"""
queryset = Role.objects.all()
serializer_class = RoleSerializer

3、URLs

配置路由

因为我们使用视图集而不是视图,所以我们可以自动为我们的API生成URL conf,只需向routers类注册视图集即可

from rest_framework import routers
from rest_framework.documentation import include_docs_urls
router = routers.DefaultRouter() 
router.register(r'users', views.UserViewSet)
router.register(r'roles', views.RoleViewSet)
urlpatterns = [
    path('api/rbac/', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('docs/', include_docs_urls(title="rest_frameworkc api")),
]

4、Settings

所有REST框架的全局设置都被保存到一个叫做REST_FRAMEWORK的配置字典中

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAdminUser', # 登录用户才可访问
],
'PAGE_SIZE': 10 # 分页相关
}

5、Serializers与Views详细使用

serializers.py

from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import User class UserCreateSerializer(ModelSerializer): class Meta:
model = User
fields = ('user', 'username', 'email', 'roles') class UserlistSerializer(ModelSerializer): class Meta:
model = User
fields = ('user', 'username', 'email', 'roles') class UserdetailSerializer(ModelSerializer): class Meta:
model = User
fields = ('user', 'username', 'email', 'roles')

view.py

from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from .serializers import *
from .models import User class UserViewSet(ModelViewSet):
def create(self, request, *args, **kwargs):
self.serializer_class = UserCreateSerializer
data = request.data.dict()
serializer = UserCreateSerializer(data=data)
if not serial.is_valid():
return Response(status=status.HTTP_400_BAD_REQUEST) serializer.save()
return Response(serializer.data) def destroy(self, request, *args, **kwargs):
pass def update(self, request, *args, **kwargs):
pass def list(self, request, *args, **kwargs):
self.serializer_class = UserListSerializer
self.queryset = User.objects.all()
return super(UserViewSet, self).list(request) def retrieve(self, request, *args, **kwargs):
pk = kwargs.get('pk', 1)
self.serializer_class = UserDetailSerializer
self.queryset = User.objects.filter(pk=pk)
return super(UserViewSet, self).retrieve(request)

create、destroy、update、list、retrieve方法都是djangoframework默认已经有的,根据请求方法的不同调用不同的处理方式

上一篇:gnu screen的用法


下一篇:Python全栈开发-Day6-面向对象编程