【问题标题】:with drf-yasg, how to supply patterns?使用drf-yasg,如何提供图案?
【发布时间】:2019-05-17 23:30:41
【问题描述】:

我已经安装了 drf-yasg,它运行良好。我遇到的问题是它是一个大应用程序,并且每种类型的前端客户端都有大量的端点,即/admin/v1/app/v1、...

所以我认为将每种类型的文档分开是个好主意,即

urlpatterns += [
     url(r'^/admin/swagger/$', admin_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
     url(r'^/app/swagger/$', app_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]

所以看起来 drf-yasg 支持这一点,通过将 patterns 提供给 get_scheme_view

admin_schema_view = get_schema_view(
    openapi.Info(
        title="API",
        default_version='v1',
        description="The set of API endpoints used.",
        terms_of_service="https://www.google.com/policies/terms/",
        contact=openapi.Contact(email="contact@me"),
        license=openapi.License(name="BSD License"),
    ),
    patterns=?????,
    validators=['flex', 'ssv'],
    public=True,
    permission_classes=(permissions.AllowAny,),
)

现在我的猜测是提供一个字符串,与定义urls 时的第一个字符串相同,例如patterns=r'^admin/v1/',,结果为:

File "/usr/local/lib/python3.6/dist- packages/rest_framework/compat.py", line 55, in get_original_route
return urlpattern.regex.pattern
AttributeError: 'str' object has no attribute 'regex'

所以使用drf-yasg docs 的文档:

patterns – 如果给定,将仅枚举这些模式以包含在 API 规范中

这里需要什么类型的对象来处理patterns?我已经尝试在 github 上查看 django-rest-framework 和 Django 源代码,但找不到真正需要的类型,它们都是非常大的项目。

【问题讨论】:

    标签: django django-rest-framework swagger


    【解决方案1】:

    经过一些实验,我发现它所期望的模式是一个 url 模式列表,而不仅仅是一个标准的 Python 正则表达式字符串。它应该与urls.py 中的标准django urlpatterns 完全相同。

    因此,假设您已将管理 API url 模式导入为admin_urlpatterns,您只需在模式选项中指定它

    admin_schema_view = get_schema_view(
    openapi.Info(
        title="API",
        default_version='v1',
        description="The set of API endpoints used.",
        terms_of_service="https://www.google.com/policies/terms/",
        contact=openapi.Contact(email="contact@me"),
        license=openapi.License(name="BSD License"),
    ),
    patterns=admin_urlpatterns,
    validators=['flex', 'ssv'],
    public=True,
    permission_classes=(permissions.AllowAny,),
    )
    

    确实很难找到任何示例,他们可能希望在文档中包含一个生动的示例

    【讨论】:

    • 没想到这么尴尬,一定是太累了想不通,非常感谢!
    • @jupiar 这完全正常。一开始对我来说也不是很明显:)
    • 我听从了你的回答,它的工作原理是它在前端看起来很好,但是当我执行请求时它们会失败,因为构建 URL 不正确。我介绍一下:patterns=[path(f'api/poll/', include(f"api_poll.urls", namespace=f'api_poll'))]。它显示了正确的端点,但是当我尝试大摇大摆地执行某些事情时,它会在 url 中添加一个额外的 poll,因此,它显示 http://host.com/api/poll/poll/... 而不是 http://host.com/api/poll/...
    • 我基本上通过修改继承自OpenAPISchemaGeneratorCustomSchemaGenerator 中的get_paths() 来修复错误。我基本上硬编码了所需的前缀api/poll 而不是api/poll/poll。这个补丁现在可以,但我想正确地修复它。
    • 我还发现,如果您将路由器(rest_framework.routers.DefaultRouter)作为模式参数(即patterns=self.router.get_urls(),)发送,前端也将正确显示。仍然需要CustomSchemaGenerator 中的补丁。
    猜你喜欢
    • 1970-01-01
    • 2022-12-06
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 2019-08-29
    相关资源
    最近更新 更多