Django3 swagger form表单

1 篇文章 0 订阅
1 篇文章 0 订阅

安装依赖

djangorestframework
drf-yasg

settings.py

INSTALLED_APPS = [
	...
    '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,
	
    # 修改accentureTest
    'DEFAULT_INFO': 'accentureTest.urls.swagger_info',  # 这里注意,更改DjangoDrfTest

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

urls.py

from django.contrib import admin
from django.urls import path, include
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions

schema_view = get_schema_view(
    openapi.Info(
        title="测试工程API",
        default_version='v1.0',
        description="测试工程接口文档",
        terms_of_service="https://www.cnblogs.com/jinjiangongzuoshi/",
        contact=openapi.Contact(email="狂师"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('tasks/', include("tasks.urls")),

    # 配置django-rest-framwork API路由
    path('api/', include('api.urls')),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),

    # 配置drf-yasg路由
    path('^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    path('swagger', 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'),
]

views.py

查询字符串
class RoleUserApiView(APIView):
    """角色用户管理"""
    role_id = openapi.Parameter("role_id", openapi.IN_QUERY, description="角色id",
                                type=openapi.TYPE_INTEGER, required=True)

    @swagger_auto_schema(
        operation_description="查询xxx",
        responses={200: "success"},
        manual_parameters=[role_id]
    )
    def get(self, request):
        role_id = request.query_params.get("role_id")
		...
        return Response({"status": "success"},status=status.HTTP_200_OK)
Body
class RoleUserApiView(APIView):
    """角色用户管理"""
    @swagger_auto_schema(
        operation_description="增加xxx",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=["role_id", "user_ids"],
            properties={
                "role_id": openapi.Schema(type=openapi.TYPE_INTEGER, description="role_id"),
                "user_ids": openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    description="user_ids",
                    items=openapi.Items(type=openapi.TYPE_INTEGER),
                ),
            },
        ),
    )
    def post(self, request):
        """一个角色对应多个用户"""
        role_id = request.data.get("role_id")
        user_ids = request.data.get("user_ids")  # 列表类型
        ...
        return Response({"status": "success"},status=status.HTTP_200_OK)
Form
from rest_framework.parsers import MultiPartParser

class UploadFileApiView(APIView):
    parser_classes = (MultiPartParser,)  # 解析form表单,注意 必须添加这一行

    name = openapi.Parameter("name", openapi.IN_FORM, description="名字", type=openapi.TYPE_STRING, required=True)
    age = openapi.Parameter("age", openapi.IN_FORM, description="年龄", type=openapi.TYPE_INTEGER, required=True)
    file = openapi.Parameter("file", openapi.IN_FORM, description="文件名", type=openapi.TYPE_FILE, required=True)

    @swagger_auto_schema(
        operation_description="上传文件",
        responses={200: "success"},
        manual_parameters=[name, age, file],
    )
    def post(self, request):
        name = request.data.get("name")
        age = request.data.get("age")
        file = request.data.get("file")
		...
        return Response("success")
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值