Django-rest-framework 建成DRF,能够帮助咱们快速构建出 django的rest full 风格的api接口。
其源码容易理解,因此咱们能够很方便的使用。python
安装django
pip install djangorestframework pip install django==2.1.1
settings.py 配置api
INSTALLED_APPS = ( ... 'rest_framework', ) # DRF 本身的配置参数, 能够暂时不用配置 REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. }
准备serializers.py文件, 这里直接使用admin的User,因此不须要准备models, serializers 的做用至关于序列化数据,将queryset中的数据取出来,组装成咱们须要的样子。ui
from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User # 要序列的model fields = ('url', 'username', 'email', 'groups') # 数据字段 class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group # 要序列的model fields = ('url', 'name') # 数据字段
准备views.py 文件, 这里使用ModelViewSet,也能够使用其余viewset,在这里先不作深刻讲解url
from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ 用户接口 """ queryset = User.objects.all().order_by('-date_joined') # 指定queryset serializer_class = UserSerializer # 指定queryset对应的serializers class GroupViewSet(viewsets.ModelViewSet): """ 用户组接口 """ queryset = Group.objects.all() # 指定queryset serializer_class = GroupSerializer # 指定queryset对应的serializers
修改url.py 文件,奖view 绑定到路由上spa
from django.urls import include, path from rest_framework import routers from tutorial.quickstart import views # 使用router注册view,绑定url映射关系, # 关于何时使用router,何时不能使用,后面奖路由的时候在深刻了解吧 router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) # 绑定view到users路由下 router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) # 登陆接口, ]
最后,将服务完整运行起来,在访问相关接口,就能够看到效果了rest