未找到“openapi-schema”的反转。“openapi-schema”不是有效的视图函数或模式名称

Aig*_*dir 5 django django-rest-framework swagger-ui

我正在尝试使用内置方法记录我的 Django REST API。这是urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.generic.base import TemplateView
from rest_framework.documentation import include_docs_urls

urlpatterns = [
    path('api/', include('api.urls')),
    path('admin/', admin.site.urls),
    path('', include('main.urls')),
    path('swagger-ui/', TemplateView.as_view(
        template_name='swagger-ui.html',
        extra_context={'schema_url': 'openapi-schema'}
    ), name='swagger-ui'),
    url(r'^.*', TemplateView.as_view(template_name="home.html")),

] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Run Code Online (Sandbox Code Playgroud)

static/templates/swagger-ui.html

<html>
  <head>
    <title>Swagger</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
  </head>
  <body>
    <div id="swagger-ui"></div>
    <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
    <script>
    
    const ui = SwaggerUIBundle({
        url: "{% url schema_url %}",
        dom_id: '#swagger-ui',
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIBundle.SwaggerUIStandalonePreset
        ],
        layout: "BaseLayout"
      })
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

但是,我不明白我们应该在哪里分配openapi-schema文件?是.yml文件还是.js?有没有办法自动生成它?

Nic*_*oen 11

schema_url应指向一个有效的OpenAPI规范。Swagger UI 可以处理 JSON 和 YAML 文件。

将 Swagger UI 指向有效架构的最简单方法是使用动态架构视图,我认为您已经略过了。

从文档:

from rest_framework.schemas import get_schema_view

    urlpatterns = [
        # ...
        # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
        #   * `title` and `description` parameters are passed to `SchemaGenerator`.
        #   * Provide view name for use with `reverse()`.
        path('openapi', get_schema_view(
            title="Your Project",
            description="API for all things …",
            version="1.0.0"
        ), name='openapi-schema'),
        # ...
    ] 
Run Code Online (Sandbox Code Playgroud)

如果您url: "{% url schema_url %}",在模板中添加此 URLpattern ,它将能够找到动态生成的架构。

  • 好吧,如果您生成了静态模式,则需要将其添加到您的 staticfiles 文件夹中(这取决于您自己的配置,有关静态文件的更多信息,请检查 https://docs.djangoproject.com/en/3.0/如何/静态文件/)。然后,您可以将 schema 的 url 包含在模板中,方法是将 `"{% url schema_url %}",` 替换为 `"{% static "&lt;path&gt;/openapi-schema.yml" %}"` (2认同)