5

我们有许多应用程序和端点,当我们处理某些功能时,更容易通过 yasg 向客户端公开某些端点。

目前我在每个应用程序中为 swagger 定义单独的 urlpatterns 并从上部 url 聚合它。

在每个应用程序中执行以下操作(选择性地包含端点)

 router_swagger.register(r'user_coupons', UserCouponViewSet)
 router_swagger.register(r'coupons', CouponViewSet)

 urlpatterns_swagger = [
     url(r'^rest_api/', include(router_swagger.urls)),
 ]

并从其他地方聚合 urlpatterns

swagger_urlpatterns = [                                                                                                                                       
]


from review.urls import urlpatterns_swagger as s1                                                                                                             
swagger_urlpatterns += s1                                                                                                                                     
from saleor.promotion.urls import urlpatterns_swagger as s2                                                                                                   
swagger_urlpatterns += s2

schema_view = get_schema_view(
    openapi.Info(
        title="2019_09",
        default_version='v1',
    ),
    public=True,
    patterns=swagger_urlpatterns,
    permission_classes=[permissions.IsAdminUser],
)


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

]

它有效,但有点乏味,想知道是否有更好的方法?

4

1 回答 1

-1

drf-yasg在实施中遵循与 DRF( https://www.django-rest-framework.org/api-guide/schemas/)相同的模式get_schema_view

您可以将 swagger 文件生成移动到一个单独的文件中,并将所有模式导入该文件,如下所示:

schema_view = get_schema_view(
    openapi.Info(
        title="API",
        default_version="v4",
        description="Some endpoints",
        contact=openapi.Contact(email="contact@snippets.local"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    patterns=s1+s2+s3
)

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

]
于 2020-05-07T18:29:58.700 回答