在Python的drf_yasg.openapi中,如何使用TYPE_STRING来处理API参数中的字符串类型
发布时间:2024-01-02 06:32:46
在Python的drf_yasg.openapi中,可以使用TYPE_STRING来处理API参数中的字符串类型。 TYPE_STRING是drf_yasg库中的一个常量,用于指定参数的数据类型为字符串。
下面是一个使用TYPE_STRING处理API参数的示例:
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from django.urls import path
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
@ api_view(['GET'])
def hello_world(request, name):
"""
Hello World API
"""
return Response({'message': f'Hello, {name}!'})
schema_view = get_schema_view(
openapi.Info(
title="API Documentation",
default_version="v1",
description="API Documentation",
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 = [
path('hello/<str:name>/', hello_world),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]
在上述示例中,我们定义了一个简单的API视图hello_world,它接受一个名为name的字符串参数。在path中使用<str:name>指定了这个参数的类型为字符串。
然后,我们使用drf_yasg.openapi中的openapi.Info类来设置API文档的基本信息,并将其传递给get_schema_view函数。get_schema_view函数将返回一个视图函数,用于生成OpenAPI文档。
最后,在urlpatterns中将这个视图函数和URL路径/hello/<str:name>/进行关联。我们还定义了一个URL路径/swagger/,用于使用Swagger UI渲染OpenAPI文档。
通过访问http://localhost:8000/swagger/即可查看生成的API文档,并进行测试。
需要注意的是,这只是一个简单的示例,你可以根据自己的需求进行扩展和定制。希望这个例子能对你有所帮助!
