本文参考自 Django REST framework 官方文档 ,创建了一个简单的 API 供 admin 用户查询与修改系统中的用户和用户组信息。
一、创建项目
$ pip install django$ pip install djangorestframework
项目初始化:
$ django-admin startproject tutorial
$ cd tutorial
$ django-admin startapp quickstart
上述命令执行后,自动生成的 tutorial 项目的目录结构如下:
tutorial
├── 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
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']
三、视图
tutorial/quickstart/views.py
from 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
from 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.pyINSTALLED_APPSrest_framework
INSTALLED_APPS = [
...
'rest_framework',
]
五、测试
$ python manage.py runserverhttphttp$ pip install httpie
获取 API 列表:
$ http -b 127.0.0.1:8000
{
"groups": "http://172.20.19.76:8000/groups/",
"users": "http://172.20.19.76:8000/users/"
}
GET 方法获取用户组信息:
$ 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 方法获取用户信息:
$ 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 方法添加新的用户组(未授权):
$ http -b POST 172.20.19.76127.0.0.1:8000/groups/ name=superuser
{
"detail": "Authentication credentials were not provided."
}
POST 方法添加新的用户组(提供 Admin 账户信息用于验证)
$ 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/"
}