Python==3.7.6
Django==2.0.7
django-rest-swagger==2.2.0
安装swagger
pip install django-rest-swagger
INSTALLED_APPS = [
...
'rest_framework_swagger',
...
]
from rest_framework.schemas import get_schema_view # 导入辅助函数get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer,OpenAPIRenderer # swagger
schema_view = get_schema_view(title='API',renderer_classes=[SwaggerUIRenderer,OpenAPIRenderer])
urlpatterns = [
path('', schema_view, name='docs'), # 配置swagger的url路径
...
]
启动Django,在浏览器输入ip:端口号即可访问swagger
我的项目一般是一个视图对应一个接口,如果一个视图对应多个请求,可以写成以下格式
from django.shortcuts import render
from django.contrib.auth.models import User,Group
from rest_framework import viewsets
from API.serializers import UserSerializer,GroupSerializer
# Create your views here.
# viewsets通过serializer_class找到对应的serializers
class UserViewSet(viewsets.ModelViewSet):
'''
retrieve:
Return a user instance.
list:
Return all users,ordered by most recent joined.
create:
Create a new user.
delete:
Remove a existing user.
partial_update:
Update one or more fields on a existing user.
update:
Update a user.
'''
queryset = User.objects.all() # 将User的所有对象赋给queryset,并返回对应值
serializer_class = UserSerializer # 指向UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
'''
retrieve:
Return a group instance.
list:
Return all groups,ordered by most recent joined.
create:
Create a new group.
delete:
Remove a existing group.
partial_update:
Update one or more fields on a existing group.
update:
Update a group.
'''
queryset = Group.objects.all()
serializer_class = GroupSerializer