1

我正在使用drf-yasg来记录我的 API,并且我有以下设置,

from django.urls import path
from drf_yasg.views import get_schema_view

public_schema_view = get_schema_view(..., urlconf='public_apis.urls')
private_schema_view = get_schema_view(..., urlconf='private_apis.urls')

urlpatterns = [
    path('public/', public_schema_view.with_ui('swagger', cache_timeout=0), name='schema-public'),
    path('private/', private_schema_view.with_ui('swagger', cache_timeout=0), name='schema-private'),
]

注意:public_schema_view分别从模块和private_schema_view中重新生成了两组不同的 URL 。public_apis.urlsprivate_apis.urls

这里我想要两个basePaths,

  1. /api/v1/public/对于public_schema_view
  2. /api/v1/private/为了private_schema_view

所以,问题是,如何在drf-yasg中设置多个自定义?basePath

4

1 回答 1

3

您可以basePath通过覆盖模式生成器类get_schema(...)的方法 来设置它,它可以通过使用参数在函数中使用 。get_schema_view(...)generator_class

模式生成器类可以通过继承drf_yasg.generators.OpenAPISchemaGenerator类来创建,

from django.urls import path
from drf_yasg.views import get_schema_view
from drf_yasg.generators import OpenAPISchemaGenerator


class PublicAPISchemeGenerator(OpenAPISchemaGenerator):
    def get_schema(self, request=None, public=False):
        schema = super().get_schema(request, public)
        schema.base_path = '/api/v1/public/'
        return schema


class PrivateAPISchemeGenerator(OpenAPISchemaGenerator):
    def get_schema(self, request=None, public=False):
        schema = super().get_schema(request, public)
        schema.base_path = '/api/v1/private/'
        return schema


public_schema_view = get_schema_view(...,
                                     urlconf='public_apis.urls',
                                     generator_class=PublicAPISchemeGenerator)
private_schema_view = get_schema_view(...,
                                      urlconf='private_apis.urls',
                                      generator_class=PrivateAPISchemeGenerator)

urlpatterns = [
    path('public/', public_schema_view.with_ui('swagger', cache_timeout=0), name='schema-public'),
    path('private/', private_schema_view.with_ui('swagger', cache_timeout=0), name='schema-private'),
]
于 2020-07-29T15:18:14.927 回答