首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django-rest-swagger:如何在docstring中指定参数类型

django-rest-swagger:如何在docstring中指定参数类型
EN

Stack Overflow用户
提问于 2014-11-09 19:47:33
回答 7查看 25.1K关注 0票数 13

我正在使用django-rest-框架和django-rest-swagger。

问题是,我直接从请求的主体中获取数据:

代码语言:javascript
复制
def put(self, request, format=None):
    """                                                                                                                                                                                                
    This text is the description for this API                                                                                                                                                          
    username -- username                                                                                                                                                                               
    password -- password                                                                                                                                                                               
    """
    username = request.DATA['username']
    password = request.DATA['password']

但是,当我尝试从swagger请求时,我无法指定“参数类型”(默认情况下它是查询,无法找到从docstring更改它的方法)。

我通过将函数build_query_params_from_docstring中的一些行从文件"introspectors.py“中更改来解决我的问题,但是我想知道是否还有其他的方法。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2015-09-15 05:50:47

更新:这个答案只适用于django-rest-swagger < 2,请参阅下面@krd的评论。

文档:http://django-rest-swagger.readthedocs.org/en/latest/yaml.html

如果您想要放置表单数据:

代码语言:javascript
复制
def put(self, request, format=None):
    """
    This text is the description for this API.

    ---
    parameters:
    - name: username
      description: Foobar long description goes here
      required: true
      type: string
      paramType: form
    - name: password
      paramType: form
      required: true
      type: string
    """
    username = request.DATA['username']
    password = request.DATA['password']

对于JSON主体,您可以执行如下操作:

代码语言:javascript
复制
def put(...):
    """
    ...

    ---
    parameters:
    - name: body
      description: JSON object containing two strings: password and username.
      required: true
      paramType: body
      pytype: RequestSerializer
    """
    ...
票数 14
EN

Stack Overflow用户

发布于 2016-12-14 13:50:19

在视图集中定义过滤器类。django-rest不再对参数执行yaml操作。您在filterclass中定义的字段将显示为openapi / swagger文档中的字段。这很整齐。

阅读完整的文件。

http://www.django-rest-framework.org/apiguide/filtering/#djangofilterbackend

代码语言:javascript
复制
from django_filters.rest_framework.filterset import FilterSet

class ProductFilter(FilterSet):

    class Meta(object):
        models = models.Product
        fields = (
            'name', 'category', 'id', )


class PurchasedProductsList(generics.ListAPIView):
    """
    Return a list of all the products that the authenticated
    user has ever purchased, with optional filtering.
    """
    model = Product
    serializer_class = ProductSerializer
    filter_class = ProductFilter

    def get_queryset(self):
        user = self.request.user
        return user.purchase_set.all()

过滤器集中定义的字段将显示在de文档中。但不会有任何描述。

票数 2
EN

Stack Overflow用户

发布于 2017-08-28 03:51:18

类似于John VanBuskirk的回答,下面是我所得到的:

实际的手册创建了文档:

drf_api/business/schema.py

代码语言:javascript
复制
# encoding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
import coreapi

schema = coreapi.Document(
    title='Business Search API',
    url='/api/v3/business/',
    content={
        'search': coreapi.Link(
            url='/',
            action='get',
            fields=[
                coreapi.Field(
                    name='what',
                    required=True,
                    location='query',
                    description='Search term'
                ),
                coreapi.Field(
                    name='where',
                    required=True,
                    location='query',
                    description='Search location'
                ),
            ],
            description='Search business listings'
        )
    }
)

然后复制get_swagger_view函数并自定义它:

drf_api/swagger.py

代码语言:javascript
复制
# encoding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
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.views import APIView
from rest_framework_swagger import renderers
from django.utils.module_loading import import_string


def get_swagger_view(schema_location):
    """
    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):
            schema = None

            try:
                schema = import_string(schema_location)
            except:
                pass

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

            return Response(schema)


    return SwaggerSchemaView.as_view()

然后将其连接到urls.py

代码语言:javascript
复制
from ..swagger import get_swagger_view
from . import views

schema_view = get_swagger_view(schema_location='drf_api.business.schema.schema')

urlpatterns = [
    url(r'^swagger/$', schema_view),
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26832510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档