drf-yasg,仅查看某些终点的更简便方法?

时间:2019-09-21 03:50:44

标签: django-rest-framework drf-yasg

我们有许多应用程序和端点,当我们使用某些功能时,通过yasg可以更容易地将某些端点暴露给客户端。

当前,我正在为每个应用中的招摇定义单独的urlpattern,并从上层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'),

]

它可以工作,但是有点乏味,想知道是否有更好的方法吗?

1 个答案:

答案 0 :(得分:-1)

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

您可以将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'),

]