django rest_framework入门

1.rest_framework的作用
1)可以对orm和非orm资源序列化
2)支持restful风格编程(POST,PUT,PATCH)
3)使用类视图编写API的view,而不是函数视图,类视图更符合代码的设计模式。
4)用户认证和权限控制

2.使用示例
功能如下:管理员查看,编辑用户,组信息
1)新建名为tutorial的Project,创建一个名为quickstart的APP
创建表,创建超级管理员

django-admin startproject tutorial
cd tutorial
django-admin startapp quickstart
python manage.py migrate
python manage.py createsuperuser

2)序列化
创建文件/tutorial/quickstart/serializers.py编写序列化相关的代码
所谓序列化是指将对象类型转换为json格式,反序列化是指将json格式转换为对象

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

3)Views
视图访问层,会在url路由中注册,访问url时,会进入到响应的视图中处理响应。

from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
# Create your views here.


class UserViewSet(viewsets.ModelViewSet):
    """
    查看,编辑用户界面
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    查看,编辑组
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

4)url注册
编写tutorial/urls.py,注册url

from django.conf.urls import url, include
from django.contrib import admin

from rest_framework import routers

from quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

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

使用router.register注册视图,将router.urls放入urlpatterns列表中

5)Settings设置

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    'PAGE_SIZE': 10
}

DEFAULT_PERMISSION_CLASSES:定义权限,只有管理员用户才能访问
PAGE_SIZE:定义分页条数

6)测试api
启动服务

python manage.py runserver

运行结果:

bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

浏览器访问,因为有了权限控制,所以要先登录

posted on 2018-05-18 19:12  迪米特  阅读(650)  评论(0编辑  收藏  举报

导航