Python接口自动化测试(16):Django接入swagger
Swagger简介
Swagger是一个规范和完整的框架,用于生成,描述,调用和可视化RESTful风格的Web服务,总体目标是使客户端和文件系统作为服务器以同样的速度来更新。每当接口有变动时,对应的接口文档也会自动更新
- swagger可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API
- swagger可以生成客户端SDK代码用于各种不同的平台上的实现
- swagger文件可以在许多不同的平台上动代码注释中自动生成
- swagger有一个强大的社区,里面有许多强悍的贡献者
安装Django-rest-swagger
pip install django-rest-swagger
setting.py文件添加django-rest-swagger应用
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', 'rest_framework_swagger', ]
views.py文件代码,添加注释内容
from django.shortcuts import render #响应http的返回内容 from django.contrib.auth.models import User,Group #导入Django自带的user和group库 from rest_framework import viewsets #viewsets用于视图的展现形式 from api.serializers import UserSerializer,GroupSerializer #导入自定义的两个序列化类 # Create your views here. class UserViewSet(viewsets.ModelViewSet): """ retrieve: Return a user instance. list: Return all users,ordered by most recently joined. create: Create a new user. delete: Remove an existing user. partial_update: Update one or more fields on an existing user. update: Update a user. """ queryset = User.objects.all() #查询user表的全部信息 serializer_class = UserSerializer #serializers_class会找到对应的Serializers class GroupViewSet(viewsets.ModelViewSet): """ retrieve: Return a groups instance. list: Return all groups,ordered by most recently joined. create: Create a new groups. delete: Remove an existing groups. partial_update: Update one or more fields on an existing groups. update: Update a groups. """ queryset = Group.objects.all() #查询Group表的全部信息 serializer_class = GroupSerializer
urls.py文件添加get_schema_view
from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework import routers #导入路由 from api import views from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import SwaggerUIRenderer,OpenAPIRenderer schema_view=get_schema_view(title="ZXJ_API",renderer_classes=[OpenAPIRenderer,SwaggerUIRenderer]) #配置路由 router = routers.DefaultRouter() #生成路由对象 router.register(r'users',views.UserViewSet) #输入users会指向views中的UserViewSet router.register(r'groups',views.GroupViewSet)#输入groups会指向views中的GroupViewSet urlpatterns = [ path('admin/', admin.site.urls), #这个路径就是http://127.0.0.1:8000/admin/ path('',include(router.urls)), #这个路径就是http://127.0.0.1:8000/ 后面可以根users或者groups path('api-auth/',include('rest_framework.urls',namespace='rest_framework')), path('docs/',schema_view,name='docs') ]
启动服务
点击接口可以进行创建user,group,也可以修改或者删除。
可以访问:http://127.0.0.1:8001/users/查看刚才创建的newuser是否创建成功