博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django集成swagger2.0以上版本
阅读量:4579 次
发布时间:2019-06-08

本文共 5720 字,大约阅读时间需要 19 分钟。

目录

一:导入模块及配置

1:导入模块

pip install django-rest-swagger

2:setings配置

在这里插入图片描述

3:查看django版本

django2.0以上不支持yml格式配置

pip list

在这里插入图片描述

二:自定义swagger

// An highlighted block#-*- coding: utf-8 -*-'''===================================@Project:wisdomShop@Author:班婕妤@Date:12/3/2020 上午11:24@Company:深圳市智慧养老宝科技有限公司@Motto:心有猛虎,细嗅蔷薇@Python_Version:3.7.3@Django_Version:2.1.5======================================='''from rest_framework.schemas import SchemaGeneratorfrom rest_framework.schemas.coreapi import LinkNode, insert_intofrom rest_framework.renderers import *from rest_framework_swagger import renderersfrom rest_framework.response import Responsefrom rest_framework.views import APIViewfrom rest_framework.permissions import AllowAny,IsAuthenticated,IsAuthenticatedOrReadOnlyfrom django.http import JsonResponseclass MySchemaGenerator(SchemaGenerator):    def get_links(self, request=None):        links = LinkNode()        paths = []        view_endpoints = []        for path, method, callback in self.endpoints:            view = self.create_view(callback, method, request)            path = self.coerce_path(path, method, view)            paths.append(path)            view_endpoints.append((path, method, view))        # Only generate the path prefix for paths that will be included        if not paths:            return None        prefix = self.determine_path_prefix(paths)        for path, method, view in view_endpoints:            if not self.has_view_permissions(path, method, view):                continue            link = view.schema.get_link(path, method, base_url=self.url)            # 添加下面这一行方便在views编写过程中自定义参数.            link._fields += self.get_core_fields(view)            subpath = path[len(prefix):]            keys = self.get_keys(subpath, method, view)            # from rest_framework.schemas.generators import LinkNode, insert_into            insert_into(links, keys, link)        return links    # 从类中取出我们自定义的参数, 交给swagger 以生成接口文档.    def get_core_fields(self, view):        return getattr(view, 'coreapi_fields', ())class SwaggerSchemaView(APIView):    _ignore_model_permissions = True    exclude_from_schema = True    permission_classes = [AllowAny]    # 此处涉及最终展示页面权限问题,如果不需要认证,则使用AllowAny,这里需要权限认证,因此使用IsAuthenticated    #permission_classes = [IsAuthenticated]    # from rest_framework.renderers import *    renderer_classes = [        CoreJSONRenderer,        renderers.OpenAPIRenderer,        renderers.SwaggerUIRenderer    ]    def get(self, request):        # 此处的titile和description属性是最终页面最上端展示的标题和描述        generator = MySchemaGenerator(title='班婕妤系统API文档',description='''心有猛虎、细嗅蔷薇''')        schema = generator.get_schema(request=request)        # from rest_framework.response import Response        return Response(schema)def DocParam(name="default", location="query",required=True, description=None, type="string",             *args, **kwargs):    return coreapi.Field(name=name, location=location,                         required=required, description=description,                         type=type)

三:url配置

// An highlighted blockfrom django.contrib import adminfrom django.urls import path,includefrom rest_framework import routersfrom zhylbwg.views import login # 导入相关APP下的views文件from zhylbwg.views import host # 导入相关APP下的views文件from django.views.generic.base import RedirectViewfrom zhylbwg.views.product_views import product_information_viewsfrom zhylbwg.views.auth_views import AuthViewfrom zhylbwg.views.premission_views import *# 导入coreapi相关模块from rest_framework.documentation import include_docs_urls# 导入自定义的schemafrom zhylbwg.util.MySchemaGenerator import SwaggerSchemaView# 自定义接口from rest_framework.schemas import get_schema_viewfrom rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRendererfrom zhylbwg.views.product_views.order_views import OrderViewschema_view = get_schema_view(title='班婕妤API接口文档', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])router = routers.DefaultRouter()urlpatterns = [    # favicon.cio    path('favicon.ico/', RedirectView.as_view(url=r'static/blog/img/favicon.ico')),    path('admin/', admin.site.urls),    path('zhylbwg/login', login.login),# swagger接口文档路由    path("zhylbwg/docs", SwaggerSchemaView.as_view()),    # path("zhylbwg/docs", schema_view,name = 'docs'), # 配置docs的url路径    path('', include(router.urls)), # 代表位于根路径的主域名(http://127.0.0.1:8080    # drf登录    path('zhylbwg/api-auth/', include('rest_framework.urls', namespace='rest_framework')),    # 测试接口    path('zhylbwg/test1', AuthView.as_view(), name='test1'),

四:编写测试类

// An highlighted block# -*- coding: utf-8 -*-'''===================================@Project:wisdomShop@Author:班婕妤@Date:10/3/2020 下午6:09@Company:深圳市智慧养老宝科技有限公司@Motto:心有猛虎,细嗅蔷薇@Python_Version:3.7.3@Django_Version:2.1.5======================================='''from django.http import JsonResponsefrom rest_framework.views import APIViewfrom zhylbwg.util.MySchemaGenerator import DocParamfrom zhylbwg.util.authenticationSelf import AuthenticationSelfORDER_DICT = {
1: {
'name': 'apple', 'price': 15 }, 2: {
'name': 'dog', 'price': 100 }}class OrderView(APIView): '''订单相关业务''' # 用coreapi_fields定义请求参数 coreapi_fields = ( DocParam(name="username", location='body', description='用户姓名'), DocParam(name="password", location='body', description='用户密码'), DocParam(name="telphone", location='body', description='用户手机号码',required=False), ) # authentication_classes = [AuthenticationSelf,] #添加局部认证 def get(self, request, *args, **kwargs): ret = {
'code': 1000, 'msg': None, 'data': None} try: ret['data'] = ORDER_DICT except Exception as e: pass return JsonResponse(ret)

五:测试

在这里插入图片描述在这里插入图片描述

转载地址:http://baqms.baihongyu.com/

你可能感兴趣的文章
异步方法 async/await
查看>>
37 数组的概念
查看>>
去掉SrollView、GrdiView、ListView、ViewPager等滑动到边缘的光晕效果
查看>>
我选择的……
查看>>
akka actor初探
查看>>
linux清理Java环境
查看>>
SharedPreferences
查看>>
java中使用session的一些细节
查看>>
浏览器输入服务器端口号来访问html网页
查看>>
hdu 6435 CSGO(最大曼哈顿距离)
查看>>
logback框架之——日志分割所带来的潜在问题
查看>>
链路追踪工具之Zipkin学习小记
查看>>
iOS中通讯录的开发
查看>>
怎么让table中的<td>内容向上对齐
查看>>
[Java] 遍历HashMap和HashMap转换成List的两种方式
查看>>
mongodb
查看>>
LeetCode 46. Permutations
查看>>
jmeter- 性能测试3:聚合报告(Aggregate Report )
查看>>
JavaScript高级程序设计---学习笔记(二)
查看>>
vim 插件的学习
查看>>