簡體   English   中英

Django Rest Swagger 2:到目前為止,是否有記錄基於 FUNCTION 視圖的 POST 請求的參數?

[英]Django Rest Swagger 2: Is there anyway so far to document parameters for POST requests of FUNCTION based views?

我正在嘗試將django-rest-swagger==2.1.1與我現有的使用djangorestframework==3.5.3項目djangorestframework==3.5.3

該項目有一些基於類的視圖和一些基於函數的視圖。 集成swagger后,它顯示“基於類的視圖”(顯然有序列化程序)的POST請求的輸入框,但不顯示“基於函數的視圖”。 這個問題已被問過幾次,我嘗試了以下解決方案:

解決方案1 解決方案2

還有其他一些人,但對我的情況不起作用。 有什么可能的方法可以為“基於函數的視圖”做到這一點,或者我必須將它們轉換為基於類的視圖?

YAML 文檔字符串解析器在 REST Swagger>=2.0 中已棄用
我所做的是覆蓋 SchemaGenerator 類以按照我自己的約定解析視圖的文檔字符串。

from rest_framework import exceptions
from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework.views import APIView

from rest_framework_swagger import renderers

import yaml
import coreapi
import urlparse

class SchemaGenerator(SchemaGenerator):
    def get_link(self, path, method, view):
        """Custom the coreapi using the func.__doc__ .

        if __doc__ of the function exist, use the __doc__ building the coreapi. else use the default serializer.

        __doc__ in yaml format, eg:

        description: the desc of this api.
        parameters:
            - name: mobile
              desc: the mobile number
              type: string
              required: true
              location: form
            - name: promotion
              desc: the activity id
              type: int
              required: true
              location: form
        """
        fields = self.get_path_fields(path, method, view)
        yaml_doc = None
        if view and view.__doc__:
            try:
                yaml_doc = yaml.load(view.__doc__)
            except:
                yaml_doc = None

        if yaml_doc and type(yaml_doc) != str:
            _method_desc = yaml_doc.get('description', '')
            params = yaml_doc.get('parameters', [])
            for i in params:
                _name = i.get('name')
                _desc = i.get('description')
                _required = i.get('required', False)
                _type = i.get('type', 'string')
                _location = i.get('location', 'form')
                field = coreapi.Field(
                    name=_name,
                    location=_location,
                    required=_required,
                    description=_desc,
                    type=_type
                )
                fields.append(field)
        else:
            _method_desc = view.__doc__ if view and view.__doc__ else ''
            fields += self.get_serializer_fields(path, method, view)
        fields += self.get_pagination_fields(path, method, view)
        fields += self.get_filter_fields(path, method, view)

        if fields and any([field.location in ('form', 'body') for field in fields]):
            encoding = self.get_encoding(path, method, view)
        else:
            encoding = None

        if self.url and path.startswith('/'):
            path = path[1:]

        return coreapi.Link(
            url=urlparse.urljoin(self.url, path),
            action=method.lower(),
            encoding=encoding,
            fields=fields,
            description=_method_desc
        )

def get_swagger_view(title=None, url=None, patterns=None, urlconf=None):
    """
    Returns schema view which renders Swagger/OpenAPI.
    """
    class SwaggerSchemaView(APIView):
        _ignore_model_permissions = True
        exclude_from_schema = True
        permission_classes = [AllowAny]
        renderer_classes = [
            CoreJSONRenderer,
            renderers.OpenAPIRenderer,
            renderers.SwaggerUIRenderer
        ]

        def get(self, request):
            generator = SchemaGenerator(
                title=title,
                url=url,
                patterns=patterns,
                urlconf=urlconf
            )
            schema = generator.get_schema(request=request)

            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document'
                )

            return Response(schema)

    return SwaggerSchemaView.as_view()

在項目結構中的任何位置創建此模塊。 project/urls.py從此模塊導入get_swagger_view 然后,從django_rest_swagger模塊中刪除get_swagger_view方法。

參考: daimon99 在 REST Swagger 問題中的評論

更新:從django-rest-framework 3.7 版開始,由於上述代碼無法正常工作,存在重大更改,解決方案將是GuillaumeCisco 的評論

您可以使用裝飾器:

from rest_framework.decorators import api_view

然后在你的函數上面使用:

@api_view(['POST'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM