1.rest_framework的做用
1)能夠對orm和非orm資源序列化
2)支持restful風格編程(POST,PUT,PATCH)
3)使用類視圖編寫API的view,而不是函數視圖,類視圖更符合代碼的設計模式。
4)用戶認證和權限控制css
2.使用示例
功能以下:管理員查看,編輯用戶,組信息
1)新建名爲tutorial的Project,建立一個名爲quickstart的APP
建立表,建立超級管理員html
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格式轉換爲對象python
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時,會進入到響應的視圖中處理響應。django
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列表中json
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:定義分頁條數api
6)測試api
啓動服務瀏覽器
python manage.py runserver
運行結果:bash
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" } ] }
瀏覽器訪問,由於有了權限控制,因此要先登陸