django restframework 使用 案例
1 setting配置
INSTALLED_APPS = [ 'rest_framework', ]
2 app内创建序列化文件
#!/usr/bin/env python #_*_coding:utf-8_*_ from django.contrib.auth.models import Group from asset.models import UserProfile # 自定义的用户验证类。自带的是User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserProfile fields = ('url', 'name', 'email', ) # 字段名 class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name')
3 app内定义单独的view rest_view.py
#!/usr/bin/env python #_*_coding:utf-8_*_ from django.contrib.auth.models import Group from rest_framework import viewsets from asset.serializers import UserSerializer, GroupSerializer from asset.models import UserProfile # 自定义的认证表 class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = UserProfile.objects.all() # 自定义的认证表 serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer
4 app内定义Url rest_url.py
#!/usr/bin/env python #_*_coding:utf-8_*_ from django.conf.urls import url, include from rest_framework import routers from asset import rest_view router = routers.DefaultRouter() router.register(r'users', rest_view.UserViewSet) router.register(r'groups', rest_view.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) # 在全局的api定义 ]
5 全局url进行配置
""" from django.conf.urls import url from django.conf.urls import include from django.contrib import admin from asset import rest_urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/',include(rest_urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]
浏览器访问:
127.0.0.1:8000/api