标签:serializers djangorestframework
这边声明一下,以下是参考官方文档来的。
新建名为dimples的django项目
在其中建立一个名为astart的APP:
# 新建目录mkdir dimplescd dimples
virtualenv envenv\Scripts\activate
pip install django pip install djangorestframework
django-admin.py startproject dimples . cd dimples django-admin.py startapp astart cd ..
python manage.py migrate
python manage.py createsuperuser
首先创建一个文件dimples/astart/serializers.py来编写序列化相关的代码:
from django.contrib.auth.models import User, Groupfrom rest_framework import serializersclass UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = (‘url‘, ‘username‘, ‘email‘, ‘groups‘)class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = (‘url‘, ‘name‘)
HyperlinkedModelSerializer: 建立超链接关系。
编写视图文件
from django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom dimples.astart.serializers import UserSerializer, GroupSerializerclass UserViewSet(viewsets.ModelViewSet): """ 查看、编辑用户的界面 """ queryset = User.objects.all().order_by(‘-date_joined‘) serializer_class = UserSerializerclass GroupViewSet(viewsets.ModelViewSet): """ 查看、编辑组的界面 """ queryset = Group.objects.all() serializer_class = GroupSerializer
ViewSets:封装许多常见的操作,减少重复代码。 保持代码的简洁以及逻辑的清晰。
from django.conf.urls import url, includefrom rest_framework import routersfrom dimples.astart import views router = routers.DefaultRouter() router.register(r‘users‘, views.UserViewSet) router.register(r‘groups‘, views.GroupViewSet)# 使用URL路由来管理我们的API# 另外添加登录相关的URLurlpatterns = [ url(r‘^‘, include(router.urls)), url(r‘^api-auth/‘, include(‘rest_framework.urls‘, namespace=‘rest_framework‘)) ]
使用了ViewSets可以通过使用Router类来自动生成URL配置信息。
启用分页功能 以及 只有管理员能访问
INSTALLED_APPS = ( ... ‘rest_framework‘, ) REST_FRAMEWORK = { ‘DEFAULT_PERMISSION_CLASSES‘: (‘rest_framework.permissions.IsAdminUser‘,), ‘PAGE_SIZE‘: 10}
Terminal中输入
python ./manage.py runserver
使用命令行工具访问API
http -a dimples:111111 http://127.0.0.1:8000/users/
(venv) C:\Users\Administrator\PycharmProjects\dimples>http -a dimples:111111 http://127.0.0.1:8000/user/HTTP/1.0 200 OKAllow: GET, HEAD, OPTIONS Content-Length: 91Content-Type: application/jsonDate: Wed, 20 Sep 2017 11:31:17 GMTServer: WSGIServer/0.1 Python/2.7.13Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "groups": "http://127.0.0.1:8000/user/groups/", "users": "http://127.0.0.1:8000/user/users/"}
确保登录状态下打开浏览器 127.0.0.1:8000/users/
本文出自 “13261842” 博客,请务必保留此出处http://13271842.blog.51cto.com/13261842/1967257
标签:serializers djangorestframework
原文地址:http://13271842.blog.51cto.com/13261842/1967257