Django REST Framework簡單入門(一)

Django REST Framework(簡稱DRF),是一個用於構建Web API的強大且靈活的工具包。

REST這個詞,是Roy Thomas Fielding在他2000年的博士論文中提出的。html

簡單來講,RESTful架構:python

   (1)每個URI表明一種資源;django

   (2)客戶端和服務器之間,傳遞這種資源的某種表現層;api

 (3)客戶端經過四個HTTP動詞(GET、POST、PUT、DELETE),對服務器端資源進行操做,實現"表現層狀態轉化"。服務器

理解restful:RESTful API 設計指南理解RESTful架構

安裝配置相關

一、安裝

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

可選安裝:restful

  • coreapi(1.32.0+) – 支持模式生成。
  • Markdown(2.1.0+) – Markdown支持可瀏覽的API。
  • django-filter(1.0.1+) – 過濾支持。
  • django-crispy-forms – 改進的HTML顯示過濾。
  • django-guardian(1.1.1+) – 支持對象級別的權限控制。

二、註冊到app

INSTALLED_APPS = (
    ...
    'rest_framework',
)

三、配置可視化api

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

 四、簡單應用

一、先建立一個模型markdown

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

二、Serializers(序列化器)架構

序列化數據,在models.py 同級目錄下新建一個serializers.pyapp

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')

三、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

三、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")),
]

 四、Settings

全部REST框架的全局設置都被保存到一個叫作REST_FRAMEWORK的配置字典中

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser', # 登陸用戶纔可訪問
    ],
    'PAGE_SIZE': 10 # 分頁相關
}

五、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默認已經有的,根據請求方法的不一樣調用不一樣的處理方式

相關文章
相關標籤/搜索