django 3.0 使用swagger

以前我们熟知的swaggger已经不再支持 django 3.0,可以使用 drf_yasg
支持如下:

Django Rest Framework: 3.8, 3.9, 3.10, 3.11
Django: 1.11, 2.2, 3.0
Python: 2.7, 3.6, 3.7, 3.8

安装drf_yasg

1
pip3 install -U drf-yasg

settings.py 开启app

1
2
3
4
5
INSTALLED_APPS = [
...
'drf_yasg',
...
]

根 url.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
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

...

schema_view = get_schema_view(
openapi.Info(
title="Snippets API",
default_version='v1',
description="Test description",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@snippets.local"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
...
]

访问/swagger 看一下吧