Как изменить положение конечных точек в drf-yasg Django

Я пытаюсь настроить документацию drf api с помощью drf-yasg. Я хочу изменить порядок отображения конечных точек. Например, изменить:

GET /endpoint/number1/
GET /endpoint/number2/ 

to

GET /endpoint/number2/
GET /endpoint/number1/

в документе swagger. Как я могу это сделать?

Это работает для меня.....

# In your urls.py

from drf_yasg.generators import OpenAPISchemaGenerator
from collections import OrderedDict

endpoints_order = [
    '/v1/upload_data/',
    '/v1/set_data/', 
    '/v1/set_target_variable/', 
    'etc', 
]
    

class CustomOpenAPISquemaGenerator(OpenAPISchemaGenerator):

    def get_paths(self, endpoints, components, request, public):
        # Copied and modified from drf_yasg source code:
        # Maybe you want to adapted the code with your drf_yasg version
        # https://drf-yasg.readthedocs.io/en/stable/_modules/drf_yasg/generators.html#OpenAPISchemaGenerator.get_paths
        if not endpoints:
            return openapi.Paths(paths={}), ''

        prefix = self.determine_path_prefix(list(endpoints.keys())) or ''
        assert '{' not in prefix, "base path cannot be templated in swagger 2.0"

        paths = OrderedDict()
        # for path, (view_cls, methods) in sorted(endpoints.items()):  # REMOVED from source
        for path in endpoints_order:                # NEW to set custom display endpoints order 
            view_cls, methods = endpoints[path]     # NEW to set custom display endpoints order 
            operations = {}
            for method, view in methods:
                if not self.should_include_endpoint(path, method, view, public):
                    continue

                operation = self.get_operation(view, path, prefix, method, components, request)
                if operation is not None:
                    operations[method.lower()] = operation

            if operations:
                # since the common prefix is used as the API basePath, it must be stripped
                # from individual paths when writing them into the swagger document
                path_suffix = path[len(prefix):]
                if not path_suffix.startswith('/'):
                    path_suffix = '/' + path_suffix
                paths[path_suffix] = self.get_path_item(path, view_cls, operations)
        return self.get_paths_object(paths), prefix


schema_view = get_schema_view(
   openapi.Info(),
   public=True,
   permission_classes=[permissions.AllowAny],
   generator_class=CustomOpenAPISquemaGenerator # Use custom Squema Generator
)

urlpatterns = [
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]

Вы можете увидеть имена ваших конечных точек с помощью:

class CustomOpenAPISquemaGenerator(OpenAPISchemaGenerator):

    def get_paths(self, endpoints, components, request, public):
        print(endpoints.keys())

Надеюсь, это поможет. С уважением.

Вернуться на верх