使用DRF管理OpenApi文档
drf-openapi3的Python项目详细描述
DRF OpenApi 3
Django REST框架的OpenApi 3实用程序
增强了DRF AutoSchema和SchemaGenerator,以帮助生成更好的openapi3文档。在
在架构生成中支持服务器、已弃用、标记和摘要, 现在,您可以标记apieviews,将它们标记为已弃用,并在描述之外显示摘要。 如果希望apieview在文档中显示自定义内容, 您可以通过将注释以YAML格式写入view/view方法来添加它。 修复了处理多个对象的视图的请求正文和响应, 如批量插入、批量更新、批量删除。现在它们显示为数组。在
安装
- 使用
pip install drf_openapi3
安装包 - 将
drf_openapi3.apps.OpenApi3Config
添加到DjangoINSTALLED_APPS
配置
- OpenApi文档视图
扩展drf_openapi3.views.OpenApiTemplateView
。您可以定义标题和模板名称,否则将使用默认值。在
fromdjango.contrib.auth.mixinsimportLoginRequiredMixinfromdrf_openapi3.viewsimportOpenApiTemplateViewclassMyOpenApiTemplateView(LoginRequiredMixin,OpenApiTemplateView):title='My OpenAPI'template_name='path/to/mytemplate.html'
- 使用
drf_openapi3.SortedPathSchemaGenerator
作为生成器类向urlpatterns添加架构
- 开始记录您的ApiViews。在
您的视图必须扩展drf_openapi3.views.AdvanceApiView
。在
fromdrf_openapi3.viewsimportAdvanceApiViewfromrest_framework.genericsimportListAPIViewclassMyAPIListView(ListAPIView,AdvanceApiView):allowed_methods=['get']defget(self,request,*args,**kwargs):returnsuper(MyAPIListView,self).list(request,*args,**kwargs)
如何使用
让我们一步一步来看看你能做些什么。在
定义多个服务器
例如,如果将测试沙盒与生产服务器一起提供,则非常有用。
在Django设置中,您可以在API_SERVERS
中定义url和描述:
API_SERVERS=[{"url":"https://test.example.com/","description":"Sandbox server (uses test data)",},{"url":"https://example.com/","description":"Production server (uses live data)",},]
如果不定义任何内容,DjangoBASE_URL
将用于构建服务器块。
因此,如果您在本地环境中开发,服务器url
将是http://localhost:8000
。
如果是生产环境,服务器url
将是https://example.com
。
请记住,在API_SERVERS
中定义多个服务器将允许用户在测试端点之前在文档的下拉列表中切换服务器url。在
将标记应用于您的apieview
如果要标记视图,只需向其添加属性tags
。
您可以自己决定,添加端点版本非常方便:
fromdrf_openapi3.viewsimportAdvanceApiViewfromrest_framework.genericsimportListAPIViewclassMyAPIListView(ListAPIView,AdvanceApiView):# ...# ...allowed_methods=['get']tags=["v2"]defget(self,request,*args,**kwargs):returnsuper(MyAPIListView,self).list(request,*args,**kwargs)
将已弃用的应用于旧的apieview
如果要将视图标记为已弃用,只需向其添加属性deprecated = True
:
fromdrf_openapi3.viewsimportAdvanceApiViewfromrest_framework.genericsimportListAPIViewclassMyAPIListView(ListAPIView,AdvanceApiView):# ...# ...allowed_methods=['get']tags=["v0"]deprecated=Truedefget(self,request,*args,**kwargs):returnsuper(MyAPIListView,self).list(request,*args,**kwargs)
使用GET以外的方法处理多个对象的视图
当编写执行批量创建、更新或删除操作的视图时,文档中会遇到一些问题:
requestBody
和{object
,但它们应该是{
通过向视图添加many = True
属性,可以告诉模式requestBody
和{
fromrest_framework.genericsimportListCreateAPIViewfromrest_framework.statusimportHTTP_400_BAD_REQUEST,HTTP_200_OKfromdrf_openapi3importAdvanceApiViewclassMyListPostView(ListCreateAPIView,AdvanceApiView):# ...# ...allowed_methods=['get','post']many=Truedefpost(self,request,*args,**kwargs)->Response:serialized=self.get_serializer(data=request.data,many=True)ifserialized.is_valid():serialized.save()returnResponse(serialized.data,status=HTTP_200_OK)returnResponse(serialized.errors,status=HTTP_400_BAD_REQUEST)
在文档中显示自定义内容
DRF AutoSchema已读取视图/视图方法Docstring:
如果要在文档中显示端点description
,
您可以在视图/视图方法Docstring中写入一些文本。
但这对我来说还不够。在
让我们从最简单的一个开始,这个已经从DRF AutoSchema实现的,它一直保持向后兼容性:
我们在视图Docstring中添加一个简单的描述。如果同时在视图和方法视图上执行此操作,则只考虑方法视图Docstring:
fromrest_framework.genericsimportListCreateAPIViewfromrest_framework.statusimportHTTP_400_BAD_REQUEST,HTTP_200_OKfromdrf_openapi3importAdvanceApiViewclassMyListPostView(ListCreateAPIView,AdvanceApiView):""" This is my endpoint description and it will be reported for each allowed method. """# ...# ...allowed_methods=['get','post']many=Truedefpost(self,request,*args,**kwargs)->Response:""" ... and that's my method description Since both the descriptions are defined you'll see only this one. You won't see "This is my endpoint description", unless you delete the text here above. """serialized=self.get_serializer(data=request.data,many=True)ifserialized.is_valid():serialized.save()returnResponse(serialized.data,status=HTTP_200_OK)returnResponse(serialized.errors,status=HTTP_400_BAD_REQUEST)
如果要管理对架构的自定义更改,只需将它们添加到YAML格式的Docstring中。 你会注意到你读代码也会更容易。在
默认情况下,DRF AutoSchema仅显示状态代码200作为示例响应。
因为400401403404状态码返回一个JSON{"detail": <error detail>}
,
在Django设置中,可以定义STATIC_ERROR_CODES = True
在文档中显示更多响应。
如果必须对视图中的响应执行进一步的更改,可以将它们放在YAML view/view方法Docstring中。在
如果你想限制你在文档上看到的允许的响应代码,
只需在视图中列出允许的状态代码(allowed_status_codes
);当您有启用
STATIC_ERROR_CODES
并且您希望阻止显示某些响应。在
我们开始有创意了,再加一个完整的例子:
classMyCommentedView(ListAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView,AdvanceApiView):""" get: summary: Summary for get method description: Description for get method post: summary: Summary for post method description: Description for post method 400: description: Invalid object, that's a custom description of 400 response code for post method put: summary: Summary for put method description: Description for put method delete: summary: Summary for delete method description: Description for delete method 200: description: Corsa objects deleted, that's a custom description of 200 response code for delete method schema: type: array items: properties: field: type: boolean description: Deleted flag, here we define a different schema for bulk delete """allowed_methods=("GET","POST","PUT","DELETE")allowed_status_codes=(200,400,401,403)tags=["v0"]many=True# ...# ...
如果您已经重写了视图方法(.get()
,.post()
,.put()
,.delete()
),那么您可以在那里编写注释。
请注意,如果您这样做,您不能使用符号method: properties
:
# ...# ...defdelete(self,request,*args,**kwargs)->Response:""" summary: Summary for delete method description: Description for delete method 200: description: Corsa objects deleted, that's a custom description of 200 response code for delete method schema: type: array items: properties: field: type: boolean description: Deleted flag, here we define a different schema for bulk delete """output=[]fordatainrequest.data:# ...# ...returnResponse(output,status=HTTP_200_OK)
小音符
该包修复了某些序列化程序字段上未正确呈现的类型映射:
- ChoiceField,现在检查正确的类型,第一个选项将作为示例显示在request body/response中
- SerializerMethodField,这里的类型是根据分配给参数
method_name
的函数的返回类型猜测的。 请参考typing以更好地理解类型提示。在
- 项目
标签: