如何改变drf-yasg Django中端点的位置



我正在尝试使用drf-yasg自定义drfapi文档。我想改变显示端点的顺序。例如修改:

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

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())

希望有帮助。问候。

最新更新