这边声明一下,以下是参考官方文档来的。
新建名为dimples的django项目
在其中建立一个名为astart的APP:
# 新建目录
mkdir dimples
cd dimples
virtualenv env
env\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, 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')
HyperlinkedModelSerializer: 建立超链接关系。
编写视图文件
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from dimples.astart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
查看、编辑用户的界面
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
查看、编辑组的界面
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
ViewSets:封装许多常见的操作,减少重复代码。 保持代码的简洁以及逻辑的清晰。
from django.conf.urls import url, include
from rest_framework import routers
from dimples.astart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# 使用URL路由来管理我们的API
# 另外添加登录相关的URL
urlpatterns = [
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 OK
Allow: GET, HEAD, OPTIONS
Content-Length: 91
Content-Type: application/json
Date: Wed, 20 Sep 2017 11:31:17 GMT
Server: WSGIServer/0.1 Python/2.7.13
Vary: 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/