Django REST framework +drf_yasg 生成swaggers在线API文档

安装

1
pip install drf-yasg

第一步:新建一个Django项目

1
django-admin.py startproject DjangoDrfTest

第二步:新建一个APP

1
python manage.py startapp news

第三步:修改settings.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
"drf_yasg"
]

SWAGGER_SETTINGS = {
'LOGIN_URL': '/admin/login',
'LOGOUT_URL': '/admin/logout',
'PERSIST_AUTH': True,
'REFETCH_SCHEMA_WITH_AUTH': True,
'REFETCH_SCHEMA_ON_LOGOUT': True,

'DEFAULT_INFO': 'DjangoDrfTest.urls.swagger_info', # 描述信息

'SECURITY_DEFINITIONS': {
'Basic': {
'type': 'basic'
},
'Bearer': {
'type': 'apiKey',
'name': 'authorization',
'in': 'header'
},
'Query': {
'type': 'apiKey',
'name': 'auth',
'in': 'query'
}
}
}

第四步:修改news/下修改views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# -*- coding: utf-8 -*-
import sys

reload(sys)
sys.setdefaultencoding("utf8")
sys.path.append('../')
# from __future__ import unicode_literals
from django.shortcuts import render
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.views import APIView
import json
from django.http import JsonResponse
from pymongo import MongoClient


def get_request_args(func):
return {}


class GetOneNews(APIView):
test_param = openapi.Parameter("id", openapi.IN_QUERY, description="test manual param",
type=openapi.TYPE_INTEGER)

@swagger_auto_schema(operation_description="partial_update description override",
responses={404: 'id not found'},
manual_parameters=[test_param])
@get_request_args
def get(self, request, args):
return JsonResponse({})


@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['id', "user_name"],
properties={
'id': openapi.Schema(type=openapi.TYPE_INTEGER),
'user_name': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
)
@get_request_args
def post(self, request, args):
return JsonResponse({})

@swagger_auto_schema 装饰器要放在所有装饰器的首位

第五步:news/下新建urls.py并添加以下内容

1
2
3
4
5
6
7
8
9
10
11
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('../')
from django.conf.urls import url
from views import *

urlpatterns = [
url(r'^getOneNews/?$', GetOneNews.as_view(), name='get_one_news'),
]

第六步:修改DjangoDrfTest/urls.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import user_agents
from django.conf.urls import include, url
from django.contrib import admin
from django.shortcuts import redirect
from rest_framework import permissions
from drf_yasg import openapi
from drf_yasg.views import get_schema_view


swagger_info = openapi.Info(
title="Snippets API",
default_version='v1',
description="""This is a demo project for the [drf-yasg](https://github.com/axnsan12/drf-yasg) Django Rest Framework library.

The `swagger-ui` view can be found [here](/cached/swagger).
The `ReDoc` view can be found [here](/cached/redoc).
The swagger YAML document can be found [here](/cached/swagger.yaml).

You can log in using the pre-existing `admin` user with password `passwordadmin`.""", # noqa

terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@snippets.local"),
license=openapi.License(name="BSD License"),
)

SchemaView = get_schema_view(
info = swagger_info,
validators=['ssv', 'flex'],
public=True,
permission_classes=(permissions.AllowAny,),
)


def root_redirect(request):
user_agent_string = request.META.get('HTTP_USER_AGENT', '')
user_agent = user_agents.parse(user_agent_string)

if user_agent.is_mobile:
schema_view = 'cschema-redoc'
else:
schema_view = 'cschema-swagger-ui'

return redirect(schema_view, permanent=True)


urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
url(r'^redoc-old/$', SchemaView.with_ui('redoc-old', cache_timeout=0), name='schema-redoc-old'),

url(r'^cached/swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=None), name='cschema-json'),
url(r'^cached/swagger/$', SchemaView.with_ui('swagger', cache_timeout=None), name='cschema-swagger-ui'),
url(r'^cached/redoc/$', SchemaView.with_ui('redoc', cache_timeout=None), name='cschema-redoc'),
url(r'^$', root_redirect),
url(r'^news/', include('news.urls', namespace="crawl_config")),
]

第七步:运行managy.py

API通过header apiKey验证或者apiKey在query中,变量的配置位置在settings.py中SWAGGER_SETTINGS配置项中

get_schema_view 参数:

  • info - Swagger API Info对象; 如果省略,则默认为DEFAULT_INFO
  • url - API基本网址; 如果留空,则将从提供视图的位置推断出
  • patterns - 传递给SchemaGenerator
  • urlconf - 传递给SchemaGenerator
  • public - 如果为False,则仅包括当前用户有权访问的端点
  • validators - 要在生成的模式上应用的验证器名称列表; 允许的值是flex,ssv
  • generator_class - 要使用的模式生成器类; 应该是的子类OpenAPISchemaGenerator
  • authentication_classes - 架构视图本身的身份验证类
  • permission_classes - 架构视图本身的权限类

get_schema_view 方法:

  • SchemaView.with_ui(renderer, cache_timeout, cache_kwargs) - 使用指定的UI渲染器获取视图实例; 之一swagger,redoc
  • SchemaView.without_ui(cache_timeout, cache_kwargs) - 获取没有UI渲染器的视图实例; 一样as_cached_view没有kwargs
  • SchemaView.as_cached_view(cache_timeout, cache_kwargs, **initkwargs)- as_view与之相同,但具有可选的缓存
  • 当然,也可以使用 as_view
  • 所有前3个方法都有两个可选参数,cache_timeout并且cache_kwargs; 如果存在,这些将传递给Django的cached_page装饰器,以便在结果视图上启用缓存。请参阅(http://drf-yasg.readthedocs.io/en/stable/readme.html#caching)。

前端显示

swagger的网页资源是和python包放置在一起。

在服务器上部署时,找到不到静态资源位置的。

所以要讲python 包下这个static文件夹复制到工程的根目录下,就可以看到前端啦

drf_yasg.utils.swagger_auto_schema

官网链接

drf_yasg.utils.swagger_auto_schema(
method=None, methods=None, auto_schema=<class ‘drf_yasg.utils.unset’>, request_body=None, query_serializer=None, manual_parameters=None, operation_id=None, operation_description=None, operation_summary=None, security=None, deprecated=None, responses=None, field_inspectors=None, filter_inspectors=None, paginator_inspectors=None, tags=None, **extra_overrides)

  • method (str) – for multi-method views, the http method the options should apply to

  • methods (list[str]) – for multi-method views, the http methods the options should apply to

  • auto_schema (drf_yasg.inspectors.SwaggerAutoSchema) – custom class to use for generating the Operation object; this overrides both the class-level swagger_schema attribute and the DEFAULT_AUTO_SCHEMA_CLASS setting, and can be set to None to prevent this operation from being generated

  • request_body (drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or rest_framework.serializers.Serializer or type[no_body]) – custom request body which will be used as the schema property of a Parameter with in: ‘body’.
    A Schema or SchemaRef is not valid if this request consumes form-data, because form and body parameters are mutually exclusive in an Operation. If you need to set custom form parameters, you can use the manual_parameters argument.
    If a Serializer class or instance is given, it will be automatically converted into a Schema used as a body Parameter, or into a list of form Parameters, as appropriate.

  • query_serializer (rest_framework.serializers.Serializer) – if you use a Serializer to parse query parameters, you can pass it here and have Parameter objects be generated automatically from it.
    If any Field on the serializer cannot be represented as a query Parameter (e.g. nested Serializers, file fields, …), the schema generation will fail with an error.
    Schema generation will also fail if the name of any Field on the query_serializer conflicts with parameters generated by filter_backends or paginator.

  • manual_parameters (list[drf_yasg.openapi.Parameter]) – a list of manual parameters to override the automatically generated ones Parameters are identified by their (name, in) combination, and any parameters given here will fully override automatically generated parameters if they collide.
    It is an error to supply form parameters when the request does not consume form-data.

  • operation_id (str) – operation ID override; the operation ID must be unique across the whole API

  • operation_description (str) – operation description override

  • operation_summary (str) – operation summary string

  • security (list[dict]) – security requirements override; used to specify which authentication mechanism is required to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted authentication schemes), and None will inherit the top-level security requirements

  • deprecated (bool) – deprecation status for operation

  • responses (dict[int or str, (drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or drf_yasg.openapi.Response or str or rest_framework.serializers.Serializer)]) – a dict of documented manual responses keyed on response status code. If no success (2xx) response is given, one will automatically be generated from the request body and http method. If any 2xx response is given the automatic response is suppressed.

    • if a plain string is given as value, a Response with no body and that string as its description will be generated
    • if None is given as a value, the response is ignored; this is mainly useful for disabling default 2xx responses, i.e. responses={200: None, 302: ‘something’}
    • if a Schema, SchemaRef is given, a Response with the schema as its body and an empty description will be generated
    • a Serializer class or instance will be converted into a Schema and treated as above
    • a Response object will be used as-is; however if its schema attribute is a Serializer, it will automatically be converted into a Schema
  • field_inspectors (list[type[drf_yasg.inspectors.FieldInspector]]) – extra serializer and field inspectors; these will be tried before ViewInspector.field_inspectors on the inspectors.SwaggerAutoSchema

  • filter_inspectors (list[type[drf_yasg.inspectors.FilterInspector]]) – extra filter inspectors; these will be tried before ViewInspector.filter_inspectors on the inspectors.SwaggerAutoSchema

  • paginator_inspectors (list[type[drf_yasg.inspectors.PaginatorInspector]]) – extra paginator inspectors; these will be tried before ViewInspector.paginator_inspectors on the inspectors.SwaggerAutoSchema

  • tags (list[str]) – tags override

  • extra_overrides – extra values that will be saved into the overrides dict; these values will be available in the handling inspectors.SwaggerAutoSchema instance via self.overrides

参考文章


Django REST framework +drf_yasg 生成swaggers在线API文档
https://flepeng.github.io/021-Python-32-框架-Django-REST-framework-Django-REST-framework-drf-yasg-生成swaggers在线API文档/
作者
Lepeng
发布于
2021年8月18日
许可协议