参考DRF-YASG官网配置

环境版本
python3.7
django2.2.16
djangorestframework3.12.4
drf_yasg1.20.0
1. 项目目录结构:
django_swagger/
	|— django_swagger/
	|    |— __init__.py
	|    |— settings.py
	|    |— urls.py
	|    |_ wsgi.py
	|— api/
	|    |— static/
	|    |— __init__.py
	|    |— admin.py
	|    |— apps.py
	|    |— models.py
	|    |— serializers.py # 新建文件
	|    |— tests.py
	|    |_ views.py # 视图文件
	|- manage.py

在django_swagger/settings.py:

INSTALLED_APPS = [
   ...
   'django.contrib.staticfiles',  # required for serving swagger ui's css/js files
   'api', # 我自己定义的业务模块
   'drf_yasg',
   ...
]
在api/下新建serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
#数据序列


class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Group
        fields = ('url', 'name')
在api/view.py
#视图
from  django.contrib.auth.models import User,Group
from rest_framework import viewsets
from  api.serializers import UserSerializer,GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    '''查看,编辑用户的界面'''
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):
    '''查看,编辑组的界面'''
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
在django_swagger/urls.py:
...
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'),
   ...
]

访问(我启动在8000端口,因人而异):http://127.0.0.1:8000/swagger/
在这里插入图片描述
点击测试groups接口
GET /groups/接口 功能正常
在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐