From 9c56a18d18e64c725567d4772bd0eee77e928db3 Mon Sep 17 00:00:00 2001 From: Daniel Kjellid Date: Thu, 8 Aug 2024 10:41:18 +0200 Subject: [PATCH] Add possibility to ignore apps + namespace in the generated schema --- django_api_decorator/schema_file.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/django_api_decorator/schema_file.py b/django_api_decorator/schema_file.py index 374605c..8419adc 100644 --- a/django_api_decorator/schema_file.py +++ b/django_api_decorator/schema_file.py @@ -5,6 +5,7 @@ from typing import Any from django.conf import settings +from django.urls.resolvers import URLResolver from .openapi import generate_api_spec @@ -19,13 +20,29 @@ def get_api_spec() -> dict[str, Any]: urlpatterns = import_module(settings.ROOT_URLCONF).urlpatterns + ignored_resolvers = getattr(settings, "API_DECORATOR_SCHEMA_IGNORED_RESOLVERS", []) + resolvers_to_ignore = [] + + # iterate through urlpatterns to find resolvers to remove. + for resolver_or_pattern in urlpatterns: + if not isinstance(resolver_or_pattern, URLResolver): + continue + + app_name, namespace = resolver_or_pattern.app_name, resolver_or_pattern.namespace + if (app_name, namespace) in ignored_resolvers: + resolvers_to_ignore.append(resolver_or_pattern) + + # Remove ignored resovlers from the urlpatterns sequence. + for resolver in resolvers_to_ignore: + urlpatterns.remove(resolver) + return generate_api_spec(urlpatterns=urlpatterns) def get_path() -> Path: if not hasattr(settings, "API_DECORATOR_SCHEMA_PATH"): raise ValueError( - "ROOT_URLCONF must be set in settings in order to save the api spec " + "API_DECORATOR_SCHEMA_PATH must be set in settings in order to save the api spec " "to a file." )