Django Rest Framework 3.5 自动生成 A

作者: treelake | 来源:发表于2016-11-08 09:31 被阅读6237次

    使用 Django Rest Framework 3.5 自动生成 API 文档
    Auto-Generate Swagger Docs for your Django API

    3.5新特性:

    • Docstrings on your API's views are now included in your schema's definition.
    • The helper method get_schema_view() has been added.
    • The schema generation code has been fully documented and outlined here.

    Django Rest Framework 3.5 附带了get_schema_view方法,这个方法会为你的模式生成Django视图,它还允许我们传入一个Renderer(渲染器)类,渲染器将​​告诉视图应该如何渲染。举个例子:

    from rest_framework.schemas import get_schema_view
    
    from rest_framework.renderers import CoreJSONRenderer
    
    schema_view = get_schema_view(
        title='A Different API',
        renderer_classes=[CoreJSONRenderer]
    )
    

    将会渲染你的api生成模式为JSON(具体来说,是遵循CoreAPI规范的JSON)
    现在,使用django-rest-swagger中现成的渲染器,从我们的API生成swagger文档非常的简单。django-rest-swagger提供了两个有用的渲染器:SwaggerUIRenderer 和 OpenAPIRenderer。我们两个都用,因为SwaggerUIRenderer实际上使用渲染的OpenAPI格式。
    让我们尝试下实现简单的api接口和自动生成文档


    bash/cmd 命令行操作
    # 安装包并构建一个django项目,最后创建管理员
    pip install Django
    pip install djangorestframework
    pip install django-rest-swagger
    django-admin startproject api
    cd api
    python manage.py makemigrations
    python manage.py migrate
    python manage.py createsuperuser
    
    api/settings.py 配置文件修改
    # 在配置文件中修改两项设置
    INSTALLED_APPS = [
        # [django core apps]
         ... # 保留之前的apps
        'rest_framework',
        'rest_framework_swagger',
    ]
    ...
    REST_FRAMEWORK = {
        # Use Django's standard `django.contrib.auth` permissions,
        # or allow read-only access for unauthenticated users.
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
        ]
    }
    
    api/urls.py 生成API
    # 为了简单,我们直接利用Django自身的基本用户模型生成api接口
    from django.conf.urls import url, include
    from django.contrib.auth.models import User
    from rest_framework import routers, serializers, viewsets
    
    # Serializers define the API representation.
    class UserSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = User
            fields = ('url', 'username', 'email', 'is_staff')
    
    # ViewSets define the view behavior.
    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer
    
    # Routers provide an easy way of automatically determining the URL conf.
    router = routers.DefaultRouter()
    router.register(r'users', UserViewSet)
    
    # Wire up our API using automatic URL routing.
    # Additionally, we include login URLs for the browsable API.
    urlpatterns = [
        url(r'^api/', include(router.urls)),
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    ]
    

    到此处,运行项目后 http://localhost:8000/api/users/ 的效果如下图,登录后可以 add, create 和 delete。下一步就是生成API的swagger文档关键步了,它显得非常简洁

    api/urls.py 添加get_schema_view辅助函数
    # existing imports
    ...
    from rest_framework.schemas import get_schema_view
    from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
    
    # existing serializer, viewset, router registrations code
    ...
    
    # Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger
    schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
    
    # Inlcude the schema view in our urls.
    urlpatterns = [
        url(r'^docs/', schema_view, name="docs"),
        url(r'^api/', include(router.urls)),
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    ]
    
    bash/cmd 运行项目
    python manage.py runserver
    

    在项目主目录运行该命令,然后在浏览器打开
    http://localhost:8000/docs/
    尝试点击List Operations和Expand Operations,这用起来很酷。我们得到了数据模型api的操作列表,使用样例,甚至可以直接在界面中填充表单来使用这些api。

    此外,Django Rest Framework 3.5 使得我们在操作旁边添加提示变得极为容易,只需要在类的文档字符串中对应合适的方法名称添加你想要的文字就行了。

    # imports and UserSerializer
    ...
    class UserViewSet(viewsets.ModelViewSet):
        """
        retrieve:
            Return a user instance.
    
        list:
            Return all users, ordered by most recently joined.
    
        create:
            Create a new user.
    
        delete:
            Remove an existing user.
    
        partial_update:
            Update one or more fields on an existing user.
    
        update:
            Update a user.
        """
        queryset = User.objects.all()
        serializer_class = UserSerializer
    
    # routing
    ...
    
    最终的api/urls.py
    # 为了简单,我们直接利用Django自身的基本用户模型生成api接口
    # just inline a simple api endpoint at 'users/' that exposes Django's base User model
    from django.conf.urls import url, include
    from django.contrib.auth.models import User
    from rest_framework import routers, serializers, viewsets
    from rest_framework.schemas import get_schema_view
    from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
    
    from django.contrib import admin
    
    # Serializers define the API representation.
    class UserSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = User
            fields = ('url', 'username', 'email', 'is_staff')
    
    # ViewSets define the view behavior.
    class UserViewSet(viewsets.ModelViewSet):
        """
        retrieve:
            Return a user instance.
    
        list:
            Return all users, ordered by most recently joined.
    
        create:
            Create a new user.
    
        delete:
            Remove an existing user.
    
        partial_update:
            Update one or more fields on an existing user.
    
        update:
            Update a user.
        """
    
        queryset = User.objects.all()
        serializer_class = UserSerializer
    
    # Routers provide an easy way of automatically determining the URL conf.
    router = routers.DefaultRouter()
    router.register(r'users', UserViewSet)
    
    # Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger
    schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
    
    # Wire up our API using automatic URL routing.
    # Additionally, we include login URLs for the browsable API.
    urlpatterns = [
        url(r'^docs/', schema_view, name="docs"),
        url(r'^api/', include(router.urls)),
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
        url(r'^admin/', admin.site.urls),
    ]
    

    相关文章

      网友评论

      • sun_wenming:请问自定义请求参数如何添加呢?
        DC_5753:@最邪恶的文明人 https://www.jianshu.com/p/d2adc71ba603
        sun_wenming:@你不知道的事_781c 您好,我的解决方案就是自定义(手写)coreapi。非常麻烦,建议放弃。你可以参考一下 https://github.com/encode/django-rest-framework/commit/e5781440fa6ccff09abc6e0566bdfdd9b84a80a1#commitcomment-29826590 提到的apistar。但我只是建议,我没有尝试,不知道会遇到什么问题。因为我正在学习go语言。
        5508ee1d4af1:兄弟 请求参数显示问题解决了没
      • 耐斯街区宅神:你好 我在settings里边设置了 restframework允许访问 可是还是有跨域问题
      • 叶同学:同问:比如我有个post
        @api_view(['POST'])
        @renderer_classes((JSONRenderer,))
        def Login(request):
        """
        A Login View will return A json which contents the Token.
        :param request:username password
        :type request:post
        :return:json
        :rtype:
        """
        这里面的注释如何写页面才会展示我要输入的两个请求参数呢?
        DC_5753:@叶业力 还得写model?目前用的coreapi,和博主说的一样,很麻烦。
        叶同学:@你不知道的事_781c 这个需要跟restframework 中的serializer搭配使用,在field中的help_text参数填写
        5508ee1d4af1:兄弟 你的post请求参数显示问题解决了没
      • 人似秋鸿:同问,自己写的 api,继承自APIVIew,如何增加参数说明啊
        DC_5753:@你不知道的事_781c https://www.jianshu.com/p/d2adc71ba603
        DC_5753:@你不知道的事_781c schema = AutoSchema (
        manual_fields=[
        coreapi.Field (name='Authorization', required=True, location='header', description='', type='string'),
        coreapi.Field (name='Zone', required=True, location='header', description='', type='string'),
        coreapi.Field (name='vxnet', required=True, location='query', description='', type='string'),
        coreapi.Field (name='service_type', required=True, location='query', description='', type='string'),
        ]

        )
        5508ee1d4af1:兄弟 请求参数显示问题解决了没
      • 2ea0a265050f:请问下,/users/users 这个接口中page这个请求参数 在代码中你是如何写的 才在swagger中有请求参数生成?
        DC_5753:https://www.jianshu.com/p/d2adc71ba603

      本文标题:Django Rest Framework 3.5 自动生成 A

      本文链接:https://www.haomeiwen.com/subject/pzpouttx.html