代码之家  ›  专栏  ›  技术社区  ›  Sudaraka Jayathilaka

将基本Url添加到Django Rest Swagger

  •  3
  • Sudaraka Jayathilaka  · 技术社区  · 7 年前

    django rest swagger .我尝试添加

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

    settings.py .但它不起作用。

    2 回复  |  直到 7 年前
        1
  •  9
  •   Sudaraka Jayathilaka    7 年前

    我找不到在swagger ui中显示基本url的方法,但我可以在中添加这样的基本url urls.py

    schema_view = get_swagger_view(title='Pastebin API',url='/pastebin/')
    

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

        2
  •  0
  •   spiderlama    7 年前

    基本上你需要设置 basePath 在OpenAPI JSON响应上。要这样做 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)
    

    URL.py:

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