将基本URL添加到Django Rest Swagger

时间:2017-07-28 09:42:58

标签: django-rest-framework swagger-ui django-rest-swagger

我无法找到将基础网址添加到django rest swagger的方法。我尝试添加

SWAGGER_SETTINGS = {
    "base_path": 'localhost:62090/',
}

settings.py。但它不起作用。

2 个答案:

答案 0 :(得分:7)

我找不到在swagger ui中显示基本网址的方法,但我可以在urls.py

中添加这样的基本网址
schema_view = get_swagger_view(title='Pastebin API',url='/pastebin/')

此代码在主机和指定的URL之间添加基本URL。

答案 1 :(得分:0)

基本上,您需要在OpenAPI JSON响应上设置basePath。要使用django_rest_swagger执行此操作:

renderers.py:

from __future__ import absolute_import, division, print_function, unicode_literals

from django.core.urlresolvers import reverse
from rest_framework_swagger import renderers


class OpenAPIRenderer(renderers.OpenAPIRenderer):
    def get_customizations(self):
        data = super(OpenAPIRenderer, self).get_customizations()
        data['basePath'] = reverse('api-root')  # your base url here
        return data

views.py:

from rest_framework import exceptions
from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework.views import APIView
from rest_framework_swagger import renderers

from .renderers import OpenAPIRenderer


class SwaggerSchemaView(APIView):
    _ignore_model_permissions = True
    exclude_from_schema = True
    permission_classes = [AllowAny]
    renderer_classes = [
        CoreJSONRenderer,
        OpenAPIRenderer,  # your OpenAPIRenderer here
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = SchemaGenerator(
            title=title,
            url=url,
            patterns=patterns,
            urlconf=urlconf
        )
        schema = generator.get_schema(request=request)

        if not schema:
            raise exceptions.ValidationError(
                'The schema generator did not return a schema Document'
            )

        return Response(schema)

urls.py:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.SwaggerSchemaView.as_view(), name='api-root'),  # your swagger view here
]