0

我目前正在使用以下 django 库 -

Django==2.2.4
django-pdb==0.6.2
django-rest-swagger==2.2.0
django-service-objects==0.5.0
django-timezone-field==3.0
django-windows-tools==0.2.1
djangorestframework==3.10.2
djongo==1.2.33

它在 Python 3.7.4 版本上运行

我面临的问题是我可以在 Autoschema 中使用 corapi.Field 生成 API 的主体部分。

class SwaggerSchemaView(APIView):
    permission_classes = [AllowAny]
    renderer_classes = [
        renderers.OpenAPIRenderer,
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = SchemaGenerator()
        schema = generator.get_schema(request=request)

        return Response(schema)
class ParseResume(APIView):
    permission_classes = [AllowAny]
    schema = AutoSchema(
        manual_fields=[
            coreapi.Field(
                "data",
                required=True,
                location="body",
                description='Send Json Data',
                type="string",
                schema=coreschema.Object(),

            )
        ]
    )

    def post(self, request):
        data = request.data
        response_data = SetConnections.parse_resume(data)
        return Response(response_data)

现在,我可以生成如下所示的 Swagger 视图 -

在此处输入图像描述

但我想通过 coreapi.Field 在这个 body 部分中添加一个示例数据,如下所示 -

{
      "id": "56-df-pt",
      "fname": "John",
      "lname": "Doe",
      "experience": {
          "employee": "Company X",
          "period": "1996 - 2002",
          "engaged_in": [
                {
                   "work": "Jr. Manager",
                   "team_size": 5,
                   "time": "Sep. 1996 - Dec. 1998"
                },
                {
                   "work": "Sr. Manager",
                   "team_size": 5,
                   "time": "Jan. 1999 - Dec. 2002"
                },
           ]
  }

我该如何添加?我现在无法更改任何版本的 Django 或 Python。

4

2 回答 2

0

经过长时间寻找有关如何在 swagger 上显示嵌套对象的解决方案后,我发现以下 python 包:

django-rest-swagger

如果序列化程序包含嵌套字段(关系),则不显示嵌套对象,我是如何找到它的?,请查看有关模式生成器的 rest-framework 网站:

https://www.django-rest-framework.org/coreapi/schemas/#third-party-packages

有一行提到了另一个名为:

drf-yasg

https://drf-yasg.readthedocs.io/en/stable/index.html

该软件包具有改进的功能,例如:嵌套模式、命名模型、响应主体、枚举/模式/最小/最大验证器、表单参数等。这样,我决定通过以下步骤安装该软件包:

pip install -U drf-yasg

安装软件包后,您必须在 settings.py 的模块列表中添加模块,并添加一些我认为合适的附加配置:

....
THIRD_APPS = [
    'rest_framework',
    'rest_framework_swagger',
    'django_filters',
    'django_celery_beat',
    'drf_yasg',
]

INSTALLED_APPS += THIRD_APPS

# Django restframework
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',
        # 'rest_framework.permissions.IsAuthenticated',
        # 'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ],
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
    ],
    'COERCE_DECIMAL_TO_STRING': False,
}

SWAGGER_SETTINGS = {
    'USE_SESSION_AUTH': True,
    'LOGIN_URL': 'rest_framework:login',
    'LOGOUT_URL': 'rest_framework:logout',
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser',
        'rest_framework.parsers.JSONParser',
    ],
    'JSON_EDITOR': False,
}

然后继续转到我的urls.py并添加以下行以生成架构视图:

  • 在apps/dol/urls.py上导入必要的模块
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
  • 在apps/dol/urls.py上配置函数的初始参数,为了不显示所有 API url,我创建了变量dol_patterns来存储需要显示的 url:
app_name = 'module_dol'
dol_patterns = [
    url(r'^dol/api/?', include('apps.dol.api.urls')),
]

SchemaView = get_schema_view(
    openapi.Info(
        title="API Interface Dol",
        default_version='v1',
        description="API REST",
        # terms_of_service="https://www.google.com/policies/terms/",
        # contact=openapi.Contact(email="email@yourdomain.com"),
        license=openapi.License(name="BSD License"),
    ),
    patterns=dol_patterns,
    public=True,
    permission_classes=(permissions.AllowAny,),
)
  • 我的主要设置/urls.py文件:
urlpatterns = [
    url(r'^api-auth/?',
        include('rest_framework.urls', namespace='rest_framework'),),
    url(r'^admin/?', admin.site.urls),
    ....
    ....
    url(r'^dol/', include('apps.dol.urls', namespace='dol'),),
]
  • 在这里,我注册的网址apps/dol/urls.py
urlpatterns = [
    ......
    ......
    url(r'^swagger(?P<format>\.json|\.yaml)$',
        SchemaView.without_ui(cache_timeout=0), name='schema-json'),
    url(r'^swagger/$',
        SchemaView.with_ui('swagger', cache_timeout=0),
        name='schema-swagger-ui'),
    url(r'^redoc/$',
        SchemaView.with_ui('redoc', cache_timeout=0),
        name='schema-redoc'),
    url(r'^api/', include('apps.dol.api.urls')),
]
  • 基于类的视图端点是使用以下泛型创建的:
from rest_framework.generics import (
    CreateAPIView, UpdateAPIView, DestroyAPIView,
)
  • 此外,这就是我的apps/dol/api/urls.py的外观:
....
....
urlpatterns = [
    re_path(r"^registration/?$",
            v.ApiDolRegistration.as_view(), name='api-registration'),
    re_path(r"warranty/(?P<coupon_number>[0-9]{5,6})/?$",
            v.ApiDolWarranty.as_view(), name='api-warranty'),
    re_path(r"rejection/(?P<coupon_number>[0-9]{5,6})/?$",
            v.ApiDolRejection.as_view(), name='api-removal'),
]

  • 最后,一旦正确配置,您将能够看到如下所示的 GUI:

在此处输入图像描述

  • 当您准备好从 GUI 测试 API 时,您将看到数据层将可编辑以修改 json 树:

在此处输入图像描述

  • 关于嵌套对象的最后一次观察,为了显示嵌套对象,您必须确保序列化程序字段具有属性 read_only=False,否则该字段将不会出现在 GUI 中。
    ....
    ....
    owner_user = ClientesSerializers(
        fields=Client.FIELDS,
        read_only=False,
    )

    class Meta:
       ....
       ....

我真的希望所提供的信息对某人有所帮助。

问候,

于 2020-07-20T01:30:13.023 回答
0

这是基于Kiran Kumar Kotari查询的更新。可以在序列化器对象中设置默认值或帮助文本,此外还可以设置默认响应,前面提到的可以通过以下步骤实现:

  • 在序列化器字段中设置default值,您可以看到序列化器字段继承自Field并且它有一个参数default

在此处输入图像描述

在此处输入图像描述

  • 要设置 a default response,请执行以下导入:
from drf_yasg.utils import swagger_auto_schema
  • 在您的视图中添加如下内容:
class YourViewName(ListAPIView):
    """ description of your view """
    permission_classes = [permissions.IsAuthenticated, ]
    authentication_classes = [authentication.BasicAuthentication, ]
    serializer_class = SerializerOfYourView

    @swagger_auto_schema(**apiutl.swagger_coupon_type_get())
    def get(self, request, *args, **kwargs):
        ....
        ...
  • 在上面的示例中,您将看到一个名为的函数swagger_coupon_type_get,对吧?这将包含以下代码:
def swagger_coupon_type_get():
    """ params for swagger decorator http method GET """
    return {
        "operation_description": """
        Get all the Coupon Type records, filters that support:
        * /dol/api/bases/tipo_cupon/?descripcion__icontains=VENTA%20A%20CLIENTE
        * /dol/api/bases/tipo_cupon?id=2
        """,
        "operation_summary": 'Coupon type list',
        "responses": {
            200: rsc.RSP_COUPON_TYPE,
            500: rsc.RSP_INTERNAL_ERROR,
        },
    }
  • 最后,在前面的示例中,您将看到具有以下描述的变量/对象,RSP_COUPON_TYPE其中将包含以下代码:

from rest_framework import status
from drf_yasg import openapi

class TipoCuponVentaSerializer(srlcommon.DynamicFieldsModelSerializer):
    """ Ćoupon Type serializer """
    class Meta:
        model = mdlcat.TipoCuponVenta
        fields = [
            'id', 'descripcion',
        ]
        # reserved for swagger
        ref_name = 'CouponType'

class ResponseSerializer(serializers.Serializer):
    """ default response schema """
    ok = serializers.IntegerField(
        help_text="Request state 0:Error, 1:Ok",
    )
    result = serializers.CharField(
        help_text="Request outcome or Error Message",
    )
    status = serializers.IntegerField(
        help_text="Http code status",
    )

class ResponseCouponType(ResponseSerializer):
    """ default response schema """
    result = TipoCuponVentaSerializer(
        help_text="List of items", many=True,
    )

    class Meta:
        ref_name = 'ResponseCouponType'


EXAMPLE_COUPON_TYPE = {
    "application/json": {
        "ok": 1,
        "result": [
            {"id": 1, "descripcion": "VENTA A CLIENTE FINAL"},
            {
                "id": 2,
                "descripcion": "VENTA A CLIENTE DIRECTO POR EL IMPORTADOR"
            },
            {"id": 3, "descripcion": "VENTA DE ACTIVOS POR EL IMPORTADOR"},
        ],
        "status": status.HTTP_200_OK,
    },
}

RSP_COUPON_TYPE = openapi.Response(
    description='Ok',
    schema=ResponseCouponType,
    examples=EXAMPLE_COUPON_TYPE,
)

这样,当您显示特定端点时

于 2021-06-14T22:44:59.647 回答