drf : 自动生成接口
自动生成接口
REST framework可以自动帮助我们生成接口文档。
接口文档以网页的方式呈现。
自动接口文档能生成的是继承自APIView
及其子类的视图。
后端写好接口,编写接口文档,给前端人员看,前端人员按照接口文档开发。
后端使用world,md写,提到git上。
公司有接口平台,后端开发在接口平台录入(yapi,或者第三方),可批量导入。
后端项目自动生成接口文档:django的drf自动生成(coerapi,swagger)
安装依赖
REST framewrok生成接口文档需要coreapi
库的支持。
pip3 install coreapi
设置接口文档访问路径
导入模块:
from rest_framework.documentation import include_docs_urls
url.py
from app01 import views
from rest_framework.routers import SimpleRouter, DefaultRouter
from django.urls import path, include
from rest_framework.documentation import include_docs_urls
router = SimpleRouter()
router.register('books', views.BookAPIView)
router.register('publish', views.PublishAPIView)
urlpatterns = [
path('', include(router.urls)),
path('docs/', include_docs_urls(title='站点页面标题'))
]
settings.py
"""
#AttributeError: 'AutoSchema' object has no attribute 'get_link'
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
# 新版drf schema_class默认用的是rest_framework.schemas.openapi.AutoSchema
}
"""
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
views.py
from rest_framework.generics import CreateAPIView,RetrieveAPIView,ListAPIView,DestroyAPIView,UpdateAPIView
class BookAPIView(ViewSetMixin, CreateAPIView,RetrieveAPIView,ListAPIView,DestroyAPIView,UpdateAPIView):
"""
list:
这个是查询所有接口。
"""
queryset = Books.objects.all()
serializer_class = BookSerializers
class PublishAPIView(ModelViewSet):
queryset = Publish.objects.all()
serializer_class = PublishSerializers