Powered by Django REST Swagger
程序员文章站
2022-07-02 20:56:59
...
Powered by Django REST Swagger
#1 环境
Python==3.7.6
Django==2.0.7
django-rest-swagger==2.2.0
安装swagger
pip install django-rest-swagger
#2 使用指南
#2.1 注册app
INSTALLED_APPS = [
...
'rest_framework_swagger',
...
]
#2.2 使用
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
推荐阅读
-
Django REST framework视图的用法
-
详解从Django Rest Framework响应中删除空字段
-
在Django下测试与调试REST API的方法详解
-
Django使用swagger生成接口文档
-
Django REST Framework批量更新rest_framework_extensions
-
Django Rest Framework之认证
-
Django rest framework基本介绍与代码示例
-
Django-Rest-Framework 权限管理源码浅析(小结)
-
Django REST Framework之版本控制
-
Django Rest framework之认证的实现代码