[英]Request & Response schema of django-rest-swagger for documenting the API in DRF
[英]django-rest-swagger UI doesn't have form for POST request body (function based view)
自從2019 年 6 月棄用django-rest-swagger以來,我將回答我的問題,我剛剛找到了 2 個可行的解決方案。
第一個將全局更改 UI。
在ping.views
(或您希望的任何其他位置)中添加以下 class。
from rest_framework.schema import AutoSchema
class CustomSchema(AutoSchema):
def __init__(self):
super(CustomSchema, self).__init__()
def get_manual_fields(self, path, method):
extra_fields = [
coreapi.Field('command', required=True, location='form', schema=String(), description='', type='', example='',
coreapi.Field('params', required=False, location='form', schema=String(), description='', type='', example='',
]
manual_fields = super().get_manual_fields(path, method)
return manual_fields + extra_fields
在 Django 項目的settings.py
中添加以下設置。
REST_FRAMEWORK = {
# Corresponding path to where you added the class
'DEFAULT_SCHEMA_CLASS': 'ping.views.CustomSchema',
}
第二種解決方案可以按視圖應用。 您可以在這里查看官方指南
使用來自 rest_framework.decorators.schema 的rest_framework.decorators.schema
覆蓋DEFAULT_SCHEMA_CLASS
。
@api_view(['POST'])
@schema(CustomSchema())
def your_view(request):
print(request.body)
return JsonResponse({'task_status': 200'})
基本上,這個想法是覆蓋DEFAULT_SCHEMA_CLASS
。 schema
一詞是他們用來指代 rest_framework 中每個視圖的rest_framework
UI 的術語。
當您使用@api_view()
裝飾基於函數的視圖時,它將為您的 function 分配一個屬性schema
,其值為來自APIView.schema
的rest_framework.views.APIView
。
rest_framework.views.APIView
將進一步調用DefaultSchema()
以從settings.py
中的REST_FRAMEWORK
配置加載DEFAULT_SCHEMA_CLASS
。
在沒有其他指定的情況下,本官方公告的DEFAULT_SCHEMA_CLASS
是rest_framework.schemas.openapi.AutoSchema
。 您可能希望將其更改為rest_framework.schemas.coreapi.AutoSchema
因為它與django_rest_swagger
兼容。
希望本教程可以幫助使用django-rest-swagger (2.2.0)
的人為他們的 Django 項目提供基於函數的視圖。
如果有什么我可以在這個問題上提供幫助的,請留下評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.