django-rest-swagger对API接口注释
2021-06-21 07:05
标签:get gen 注释 系统 iss html targe nbsp eve Swagger是一个API开发者的工具框架,用于生成、描述、调用和可视化RESTful风格的Web服务。总体目标是使客户端和文件系统服务器以同样的速度来更新,方法,参数和模型紧密集成到服务器端的代码中,允许API始终保持同步。 在使用 django-rest-framework 进行API开发,可以使用django-rest-swagger接入swagger自动生成接口文档。 1. 安装django-rest-swagger 2.配置settings.py 3. views.py 该博文的项目是django-rest-framework中文站点的例子:https://q1mi.github.io/Django-REST-framework-documentation 当需要对接口的各种方法进行注释时,直接在该类下添加注释,如下所示。需要注意是的:注释的方法名称(如 get、post)要对应该类所含的方法名称 3.配置urls.py 运行manage.py后,浏览器访问 http://127.0.0.1:8000/,可以看到以下内容: 访问 http://127.0.0.1:8000/docs/,可以看到接口文档如下: 点击打开snippets,可以看到如下,每个方法后面都有你在views.py中添加的注释 点击打开get方法,如下 django-rest-swagger对API接口注释 标签:get gen 注释 系统 iss html targe nbsp eve 原文地址:https://www.cnblogs.com/delav/p/10242017.htmlpip install django-rest-swagger
INSTALLED_APPS = [
...
‘rest_framework_swagger‘
...
]
class SnippetList(generics.ListCreateAPIView):
"""
get:
Return all snippets.
post:
Create a new snippet instance.
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
"""
get:
Return a snippet instance.
put:
Update a snippet instance.
patch:
Update a snippet instance.
delete:
Delete a snippet instance.
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
class UserList(generics.ListAPIView):
"""
get:
Return all users
"""
queryset = MyUser.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
"""
get:
Return a user instance
"""
queryset = MyUser.objects.all()
serializer_class = UserSerializer
class SnippetHighlight(generics.GenericAPIView):
"""
get:
Return a highlight instance
"""
queryset = Snippet.objects.all()
renderer_classes = (renderers.StaticHTMLRenderer,)
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPICodec
schema_view = get_schema_view(title=‘API‘, renderer_classes=[SwaggerUIRenderer, OpenAPICodec])
urlpatterns = [
...
url(r‘docs/‘, schema_view, name=‘docs‘)
...
]
上一篇:Build to win!