本文共 5720 字,大约阅读时间需要 19 分钟。
pip install django-rest-swagger
django2.0以上不支持yml格式配置
pip list
// 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)
// 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/