drf-yasg:如何隐藏 Django 休息框架架构?
drf-yasg: How to hide Django rest Framework schema?
我使用 drf_yasg swagger 作为我的 Django API。
我想知道如何轻松禁用模式和模型。
screenshot
这是我的代码:
from .models import Articles
from .serializers import ArticlesSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import SessionAuthentication,TokenAuthentication, BasicAuthentication
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.parsers import JSONParser
from django.utils.decorators import method_decorator
from django.contrib.auth import authenticate, login, logout
from rest_framework.decorators import api_view
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
@swagger_auto_schema(methods=['get'], operation_description="description", manual_parameters=[
openapi.Parameter('category', openapi.IN_QUERY, "category1, category2, category3", type=openapi.TYPE_STRING),
openapi.Parameter('name', openapi.IN_QUERY, "full name", type=openapi.TYPE_STRING),
], responses={
200: openapi.Response('Response', ArticlesSerializer),
}, tags=['Articles'])
# desactivate POST methode on swagger
@swagger_auto_schema(method='POST', auto_schema=None)
@api_view(['GET','POST'])
def articles(request):
"""
List all articles.
"""
if request.user.is_authenticated:
if request.method == 'GET':
articles = Articles.objects.all()
serializer = ArticlesSerializer(Articles, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = ArticlesSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
return JsonResponse({"status":"403", "message":"User not authenticated"})
如果我添加这个
class UserList(APIView):
swagger_schema = None
我收到错误:
AssertionError: `method` or `methods` can only be specified on @action or @api_view views
已编辑代码:
文章功能非常简单,与 API 无关,只有 Python 代码。
这里的观点Class也很简单
Class 观看次数:
from django.db import models
class Articles(models.Model):
STATUS = (
(1, 'PENDING'),
(2, 'COMPLETED'),
(3, 'DECLINED'),
(0, 'BANNED'),
)
name = models.CharField(max_length=100)
...
status = models.PositiveSmallIntegerField(
choices = STATUS,
default = 1,
)
我只有一半的答案,要禁用模型,我将其添加到我的 setting.py
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',
],
}
信用转至 this guys, and here is the documentation 了解更多详情。
我终于明白了。
我只需要用纯文本、markdown 或 html.
覆盖响应参数
@swagger_auto_schema(methods=['get'], operation_description="Get article information ", manual_parameters=[
openapi.Parameter('id', openapi.IN_QUERY, "Article Id", type=openapi.TYPE_STRING),
], responses={ 200: '**Example:** \
<div class="highlight-code"><pre>{ <br>\
"category": "string", <br>\
"image": "string",<br>\
"link": "string",<br>\
"birth_date": "string",<br>\
}</pre></div>'},
tags=['Get Articles'])
要获得相同的 css 效果(背景黑色),您可以在文件中添加此自定义 CSS ...\site-packages\drf_yasg\static\drf-yasg\style.css
.swagger-ui .markdown .highlight-code pre{
color: #fff;
font-weight: 400;
white-space: pre-wrap;
background: #41444e;
padding: 15px;
}
我使用 drf_yasg swagger 作为我的 Django API。 我想知道如何轻松禁用模式和模型。 screenshot
这是我的代码:
from .models import Articles
from .serializers import ArticlesSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import SessionAuthentication,TokenAuthentication, BasicAuthentication
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.parsers import JSONParser
from django.utils.decorators import method_decorator
from django.contrib.auth import authenticate, login, logout
from rest_framework.decorators import api_view
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
@swagger_auto_schema(methods=['get'], operation_description="description", manual_parameters=[
openapi.Parameter('category', openapi.IN_QUERY, "category1, category2, category3", type=openapi.TYPE_STRING),
openapi.Parameter('name', openapi.IN_QUERY, "full name", type=openapi.TYPE_STRING),
], responses={
200: openapi.Response('Response', ArticlesSerializer),
}, tags=['Articles'])
# desactivate POST methode on swagger
@swagger_auto_schema(method='POST', auto_schema=None)
@api_view(['GET','POST'])
def articles(request):
"""
List all articles.
"""
if request.user.is_authenticated:
if request.method == 'GET':
articles = Articles.objects.all()
serializer = ArticlesSerializer(Articles, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = ArticlesSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
return JsonResponse({"status":"403", "message":"User not authenticated"})
如果我添加这个
class UserList(APIView):
swagger_schema = None
我收到错误:
AssertionError: `method` or `methods` can only be specified on @action or @api_view views
已编辑代码: 文章功能非常简单,与 API 无关,只有 Python 代码。
这里的观点Class也很简单
Class 观看次数:
from django.db import models
class Articles(models.Model):
STATUS = (
(1, 'PENDING'),
(2, 'COMPLETED'),
(3, 'DECLINED'),
(0, 'BANNED'),
)
name = models.CharField(max_length=100)
...
status = models.PositiveSmallIntegerField(
choices = STATUS,
default = 1,
)
我只有一半的答案,要禁用模型,我将其添加到我的 setting.py
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',
],
}
信用转至 this guys, and here is the documentation 了解更多详情。
我终于明白了。 我只需要用纯文本、markdown 或 html.
覆盖响应参数@swagger_auto_schema(methods=['get'], operation_description="Get article information ", manual_parameters=[
openapi.Parameter('id', openapi.IN_QUERY, "Article Id", type=openapi.TYPE_STRING),
], responses={ 200: '**Example:** \
<div class="highlight-code"><pre>{ <br>\
"category": "string", <br>\
"image": "string",<br>\
"link": "string",<br>\
"birth_date": "string",<br>\
}</pre></div>'},
tags=['Get Articles'])
要获得相同的 css 效果(背景黑色),您可以在文件中添加此自定义 CSS ...\site-packages\drf_yasg\static\drf-yasg\style.css
.swagger-ui .markdown .highlight-code pre{
color: #fff;
font-weight: 400;
white-space: pre-wrap;
background: #41444e;
padding: 15px;
}