本文参考自 Django REST framework 官方文档 ,创建了一个简单的 API 供 admin 用户查询与修改系统中的用户和用户组信息。
一、创建项目
安装依赖库:$ pip install django
$ pip install djangorestframework
项目初始化:1
2
3$ django-admin startproject tutorial
$ cd tutorial
$ django-admin startapp quickstart
上述命令执行后,自动生成的 tutorial 项目的目录结构如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16tutorial
├── manage.py
├── quickstart
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── tutorial
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
执行以下命令迁移数据库并创建管理员用户:$ python manage.py migrate
$ python manage.py createsuperuser
二、序列化
创建 tutorial/quickstart/serializers.py
文件并输入以下内容:1
2
3
4
5
6
7
8
9
10
11
12
13
14from 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']
三、视图
修改 tutorial/quickstart/views.py
视图文件:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21from django.contrib.auth.models import User, Group
from rest_framework import viewsets, permissions
from quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
四、URLs 和设置
编辑 tutorial/tutorial/urls.py
路由配置文件:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('admin/', admin.site.urls),
]
编辑 tutorial/tutorial/settings.py
文件,在 INSTALLED_APPS
配置中添加上 rest_framework
项目:1
2
3
4INSTALLED_APPS = [
...
'rest_framework',
]
五、测试
运行 $ python manage.py runserver
命令启动测试服务;
使用 http
命令对 API 进行访问测试(如未安装 http
工具,运行以下命令安装 $ pip install httpie
)。
获取 API 列表:1
2
3
4
5$ http -b 127.0.0.1:8000
{
"groups": "http://172.20.19.76:8000/groups/",
"users": "http://172.20.19.76:8000/users/"
}
GET 方法获取用户组信息:1
2
3
4
5
6
7
8
9
10
11$ http -b 127.0.0.1:8000/groups/
[
{
"name": "admin",
"url": "http://172.20.19.76:8000/groups/1/"
},
{
"name": "staff",
"url": "http://172.20.19.76:8000/groups/2/"
}
]
GET 方法获取用户信息:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19$ http -b 127.0.0.1:8000/users/
[
{
"email": "starky@test.com",
"groups": [
"http://172.20.19.76:8000/groups/2/"
],
"url": "http://172.20.19.76:8000/users/2/",
"username": "starky"
},
{
"email": "admin@test.com",
"groups": [
"http://172.20.19.76:8000/groups/1/"
],
"url": "http://172.20.19.76:8000/users/1/",
"username": "admin"
}
]
POST 方法添加新的用户组(未授权):1
2
3
4$ http -b POST 172.20.19.76127.0.0.1:8000/groups/ name=superuser
{
"detail": "Authentication credentials were not provided."
}
POST 方法添加新的用户组(提供 Admin 账户信息用于验证)1
2
3
4
5$ http -b -a admin:123456 POST 127.0.0.1:8000/groups/ name=superuser
{
"name": "superuser",
"url": "http://172.20.19.76:8000/groups/3/"
}
六、Web 界面
访问 http://127.0.0.1:8000,截图如下:
登录后支持 POST 操作,截图如下: