python - Django 2.x drf-yasg 如何在自定义方法中创建 API(如 Swagger )

标签 python django django-rest-framework swagger drf-yasg

我正在将我的 Django 1.11.7 迁移到 2.x。问题之一是 django-rest-swagger,现在已弃用。 drf-yasg 现在应该是 API 文档和创建的方式。我需要以类似于创建自定义 api 的方式进行操作,因为它不会破坏移动设备中的任何内容。

以前是这样的(django-rest-swagger==2.1.1)

old deprecated swagger 2.1.1 这是在 Django 1.11.7 和 django-rest-swagger==2.1.1 中运行良好的旧代码片段:

using swagger_schema.py
https://gist.github.com/axilaris/2f72fef8f30c56d5befe9e31cd76eb50


in url.py:

from rest_framework_swagger.views import get_swagger_view
from myapp.swagger_schema import SwaggerSchemaView


urlpatterns = [  
   url(r'^swaggerdoc/', SwaggerSchemaView.as_view()),
   url(r'^api/v1/general/get_countries$', api.get_countries, name='get_countries'),


in api.py:
@api_view(['POST'])
def get_countries(request):
    # ----- YAML below for Swagger -----
    """
    description: countries list
    parameters:
      - name: token
        type: string
        required: true
        location: form   
    """
    ......
    return Response(countries_list, status=status.HTTP_200_OK)

我的问题是如何在 drf-yasg 中类似地执行此操作,因为我想迁移此代码并且不破坏移动设备上的任何内容。

可能尝试在这个最新的稳定版本上这样做:

djangorestframework==3.9
drf-yasg==1.16.1

最佳答案

您可以在您的 api.py 中这样做。这将生成您在屏幕截图中显示的内容:

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema

from rest_framework.decorators import api_view, parser_classes
from rest_framework.parsers import FormParser

token = openapi.Parameter('token', openapi.IN_FORM, type=openapi.TYPE_STRING, required=True)


@swagger_auto_schema(
    method="post",
    manual_parameters=[token]
)
@api_view(["POST"])
@parser_classes([FormParser])
def get_countries(request):
    """
    Countries list
    """
    ......
    return Response(countries_list, status=status.HTTP_200_OK)

请注意,我添加了 @parser_classes([FormParser]) 装饰器以确保 View 接受表单数据。如果您的所有端点仅使用表单数据并且您可以删除它 set it globally in DRF settings .

结果: result

Here's more documentation on @swagger_auto_schema decorator .

关于python - Django 2.x drf-yasg 如何在自定义方法中创建 API(如 Swagger ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57898209/

相关文章:

python - 如何让字符串列的所有包含匹配项?

python - 如何使用 django 在项目内仅迁移一个应用程序

django - 在 Django/DRF 中正确处理日期时间/时区

mongodb - EmbeddedDocumentSerializer 为每个 ReferenceField 运行查询

django - 如何在 Django Rest swagger 中传递 post 参数?

python - 我应该使用哪个 Python XML 库?

python - PIL : Image. fromarray(img.astype ('uint8' ), mode ='RGB' ) 返回灰度图像

python - Pandas 数据框数据透视表和分组

python - 在 Django 模板中创建排序选项

django - 电子邮件已保存到谁知道的位置,但未找到关系