【django】drf-yasg配置使用

pip install drf-yasg

  1. settings配置
    *** request body: post put patch delete… ***
    manual_parameters: get
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',   # DRF
    'corsheaders',   # cores跨域
    'drf_yasg',   # 在线接口文档
]

# 在线swagger文档配置信息
SWAGGER_SETTINGS = {
    'DEFAULT_FIELD_INSPECTORS': [
        'drf_yasg.inspectors.CamelCaseJSONFilter',
        'drf_yasg.inspectors.InlineSerializerInspector',
        'drf_yasg.inspectors.RelatedFieldInspector',
        'drf_yasg.inspectors.ChoiceFieldInspector',
        'drf_yasg.inspectors.FileFieldInspector',
        'drf_yasg.inspectors.DictFieldInspector',
        'drf_yasg.inspectors.SimpleFieldInspector',
        'drf_yasg.inspectors.StringDefaultFieldInspector',
    ],
}
  1. 主urls配置
from django.urls import include, re_path, path
# drf_yasg 从这里开始
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
 
# drf_yasg配置
schema_view = get_schema_view(
    openapi.Info(
        title="Tweet API",
        default_version='v1',
        description="Welcome to the world of Tweet",
        terms_of_service="https://www.tweet.org",
        contact=openapi.Contact(email="demo@tweet.org"),
        license=openapi.License(name="Awesome IP"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),  # 权限类
)

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

    re_path(r'user/', include('users.urls')),   # 用户
]

  1. 视图配置
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema


class AddressViewSet(
    CreateModelMixin,
    UpdateModelMixin,
    GenericViewSet
):
    """用户收货地址"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer

    def get_queryset(self):
        ...
     
	@swagger_auto_schema(
        operation_summary='xxx',
        operation_description="",
        manual_parameters=[
            openapi.Parameter(
                "prompt",
                openapi.IN_QUERY,
                description="输入内容",
                required=True,
                type=openapi.TYPE_STRING
            ),
            openapi.Parameter(
                "model",
                openapi.IN_QUERY,
                description="识别",
                type=openapi.TYPE_STRING,
                default="test"
            ),
            openapi.Parameter(
                "max_tokens",
                openapi.IN_QUERY,
                description="限制长度",
                type=openapi.TYPE_INTEGER,
                default=2000
            ),
        ],
        responses={200: "ok", "data": "xxx返回内容"}
    )
    def list(self, request, *args, **kwargs):
        """列表"""
        ...
    
    @swagger_auto_schema(
        operation_summary='新增用户收货地址', 
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                "provice_id": openapi.Schema(
                    description='省id',
                    type=openapi.TYPE_STRING,
                    required="true"
                ),
                "city_id": openapi.Schema(
                    description='市id',
                    type=openapi.TYPE_STRING,
                    required="true"
                ),
                'district_id': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='区id',
                    required="true"
                ),
                'title': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='地址标题',
                    required="true"
                ),
                'receiver': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='收货地址',
                    required="true"
                ),
                'place': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='详细地址',
                    required="true"
                ),
                'mobile': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='手机号',
                    required="true"
                ),
                'tel': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='固定电话',
                    required="false"
                ),
                'email': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description='电子邮箱',
                    required="false"
                )
            }
        ),
        responses={200: "ok", "data": ""}
    )
    def create(self, request, *args, **kwargs):
        """新增"""
        ...

    # delete /user/addresses/<pk>/
    # pk: 地址id
    def destroy(self, request, *args, **kwargs):
        """delete: 删除"""
        ...
    
    # put /user/addresses/<pk>/status/
    # pk: 地址id
    @action(methods=["put"], detail=True)
    def status(self, request, pk=None):
        """设置默认地址"""
        ...

  1. 访问:http://127.0.0.1:8000/doc/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值