> 技术 > Django > Django搭建个人博客 | 使用插件REST framework编写RESTful API接口

Django搭建个人博客 | 使用插件REST framework编写RESTful API接口

2019-06-24 362 阅读 0 评论

前后端分离技术一般借助API技术实现,RESTful API现在比较主流且实用,推荐阅读:RESTful 架构详解。使用 Django 常规方法可以实现REST,但 Django 的强大的第三方插件库 djangorestframework ,通过在 Django 里面配置就可以把 app 的 models 中的各个表实现 RESTful API,推荐阅读:REST framework 官网

配置准备

打开虚拟环境,下载插件

pip install djangorestframework

创建用于管理API的应用

python manage.py startapp RESTfulApi

注册插件与应用

#Myblog/Myblog/settings.py

INSTALLED_APPS = (
  ...
  'rest_framework',
  'RESTfulApi‘,
)

创建序列化类

创建序列化 Serializer 类, 提供序列化和反序列化的途径,使之可以转化为某种表现形式如 JSON。我们可以借助 serializer 来实现类似于 Django 表单(form)的运作方式。在RESTfulApi 目录下,创建文件 serializers.py

#Myblog/RESTfulApi/serializers.py

from rest_framework import serializers
from Myaccount.models import User
from Storm.models import Article, Tag, Category,FriendLink
from Comment.models import Comment,UserLike

#用户信息
class UserSerializer(serializers.ModelSerializer):
    class Meta:
      model = User
      fields = ('id', 'username', 'link', 'avatar','email') #插件allauth中关联User模型定义的email字段

#标签
class TagSerializer(serializers.ModelSerializer):
    class Meta:
      model = Tag
      fields = '__all__'

#分类
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
      model = Category
      fields = '__all__' #指定字段

#文章
class ArticleSerializer(serializers.ModelSerializer):
    #自定义字段覆盖默认字段
    author = serializers.ReadOnlyField(source='author.username') #自定义作者名字字段
    keywords = serializers.SlugRelatedField( #自定义关键字字段(只关联name)
      many=True, #一对多
      read_only=True, #只读字段
      slug_field='name'
    )
    category = CategorySerializer(read_only=True) #嵌套序列
    tags = TagSerializer( #嵌套序列
      many=True, #一对多
      read_only=True, #只读字段
    )

    class Meta:
      model = Article
      exclude = ('body',)#除去指定的某些字段

#评论
class CommentSerializer(serializers.ModelSerializer):
    class Meta:
      model = Comment
      fields = '__all__' #指定字段

#用户点赞文章
class UserLikeSerializer(serializers.ModelSerializer):
    class Meta:
      model = UserLike
      fields = '__all__' #指定字段

#友情链接
class FriendLinkSerializer(serializers.ModelSerializer):
    class Meta:
      model = FriendLink
      fields = ('name','link')#指定字段

构建 View

首先设置权限:

#Myblog/RESTfulApi/permissions.py

from rest_framework import permissions

class IsAdminUserOrReadOnly(permissions.BasePermission):
    #只允许作者修改但允许所有人读的权限设置
    def has_permission(self, request, view):
      if request.method in permissions.SAFE_METHODS:
      return True
    # 写入权限需要作者本人
    return request.user and request.user.is_staff

用 viewsets 构建 View:

#Myblog/RESTfulApi/views.py

from django.shortcuts import render
from rest_framework import viewsets, permissions
from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly

from Myaccount.models import User
from Comment.models import Comment,UserLike
from Storm.models import Article, Tag, Category,FriendLink
from .serializers import UserSerializer, ArticleSerializer, TagSerializer, CategorySerializer,FriendLinkSerializer,CommentSerializer,UserLikeSerializer

# 用 viewsets 构建 View
class UserListSet(viewsets.ModelViewSet):
    # 处理 /api/users/ GET, 处理 /api/users/<pk>/ GET
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)

class TagListSet(viewsets.ModelViewSet):
    # 处理 /api/tags/ GET POST, 处理 /api/tags/<pk>/ GET
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)

class FriendLinkListSet(viewsets.ModelViewSet):
    # 处理 /api/friendLink/ GET POST, 处理 /api/friendLinks/<pk>/ GET
    queryset = FriendLink.objects.all()
    serializer_class = TagSerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)

class CategoryListSet(viewsets.ModelViewSet):
    # 处理 /api/categorys/ GET POST, 处理 /api/categorys/<pk>/ GET
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)

class ArticleListSet(viewsets.ModelViewSet):
    # 处理 /api/articles/ GET POST , 处理 /api/articles/<pk>/ GET PUT PATCH DELETE
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)
    # 重写 perform_create, user 信息不在 request.data 中, 在保存时加入 user 信息
    def perform_create(self,serializer):
        serializer.save(author=self.request.user)

class CommentListSet(viewsets.ModelViewSet):
    # 处理 /api/comment/ GET POST, 处理 /api/comment/<pk>/ GET
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)

class UserLikeListSet(viewsets.ModelViewSet):
    # 处理 /api/userlikes/ GET POST, 处理 /api/userlikes/<pk>/ GET
    queryset = UserLike.objects.all()
    serializer_class = UserLikeSerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)

配置API路由

因为使用的是 viewsets 所有通过 router 构建 urls 非常简单,include(router.urls) 会帮我们直接生成好相应的API的url:

#Myblog/urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('restAPI.urls'))
]
#Myblog/RESTfulApi/urls.py

from django.urls import path
from django.conf.urls import re_path,include
from . import views as api_views
from rest_framework.routers import DefaultRouter

app_name='RESTfulApi'

router = DefaultRouter()
router.register(r'users', api_views.UserListSet)
router.register(r'articles', api_views.ArticleListSet)
router.register(r'tags', api_views.TagListSet)
router.register(r'categorys', api_views.CategoryListSet)
router.register(r'friendLink', api_views.FriendLinkListSet)
router.register(r'comment', api_views.CommentListSet)
router.register(r'userlike', api_views.UserLikeListSet)


urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls')),
]

API ROOT: api/users:

博客源码:Github地址
参考:利用 Django REST framework 编写 RESTful APIdjango rest framework serializers小结

0 评论
 支持Markdown