欢迎访问宙启技术站
智能推送

Python中如何使用drf_yasg.openapi来生成OpenAPI文档

发布时间:2023-12-28 04:36:45

在Python中使用drf_yasg打造OpenAPI文档的过程可以分为以下几个步骤:

1. 安装drf_yasg和Swagger UI:

pip install drf_yasg
pip install django-statickit

2. 设置settings.py:

在Django项目的settings.py文件中添加以下配置:

INSTALLED_APPS = [
    # ...
    'drf_yasg',
]

STATIC_URL = '/static/'

MIDDLEWARE = [
    # ...
    'django.contrib.staticfiles.middleware.StaticFilesMiddleware',
]

STATIC_ROOT = '/path_to_static_folder'

3. 在urls.py中配置drf_yasg的路由:

from django.conf.urls import url
from django.urls import path
from django.views.generic import RedirectView
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="API文档",
      default_version='v1',
      description="API列表",
      terms_of_service="https://www.example.com/policies/terms/",
      contact=openapi.Contact(email="contact@example.com"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    url(r'^$', RedirectView.as_view(url='/swagger/')),
    url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]

现在,你可以通过访问http://localhost:8000/swagger/来查看你的API文档了。

4. 在views.py中使用drf_yasg的装饰器来为API添加描述和注解:

from rest_framework.decorators import api_view
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema

@swagger_auto_schema(method='GET', operation_description="获取用户列表", responses={200: UserSerializer(many=True)})
@api_view(['GET'])
def user_list(request):
    """
    获取用户列表
    """
    users = User.objects.all()
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data)

在上面的例子中,我们使用了swagger_auto_schema装饰器为user_list这个API添加了描述和注解。我们通过operation_description参数设置了API的简要描述,通过responses参数指定了返回结果的数据结构。在这个例子中,我们使用了UserSerializer来描述返回结果的结构。

5. 在serializers.py中定义返回结果的数据结构:

from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    email = serializers.EmailField()

在这个例子中,我们使用了Serializers来定义返回结果的结构。通过使用不同的字段类型,我们可以更细致地定义数据结构。

通过以上步骤,我们成功使用drf_yasg创建了一个带有注解和描述的OpenAPI文档,并且可以通过Swagger UI进行查看。在实际开发中,我们可以继续使用drf_yasg提供的其他特性来进一步完善我们的API文档,比如添加权限控制、分组等。