Skip to content

Commit

Permalink
allow raw JS in Swagger settings #457
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Aug 24, 2021
1 parent d5b52a3 commit 0ed0b80
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
2 changes: 2 additions & 0 deletions drf_spectacular/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@

# Dictionary of general configuration to pass to the SwaggerUI({ ... })
# https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/
# The settings are serialized with json.dumps(). If you need customized JS, use a
# string instead. The string must then contain valid JS and is passed unchanged.
'SWAGGER_UI_SETTINGS': {
'deepLinking': True,
},
Expand Down
11 changes: 7 additions & 4 deletions drf_spectacular/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,16 @@ def get(self, request, *args, **kwargs):
url=schema_url,
lang=request.GET.get('lang')
),
'settings': json.dumps(spectacular_settings.SWAGGER_UI_SETTINGS),
'oauth2_config': json.dumps(spectacular_settings.SWAGGER_UI_OAUTH2_CONFIG),
'settings': self._dump(spectacular_settings.SWAGGER_UI_SETTINGS),
'oauth2_config': self._dump(spectacular_settings.SWAGGER_UI_OAUTH2_CONFIG),
'template_name_js': self.template_name_js
},
template_name=self.template_name,
)

def _dump(self, data):
return data if isinstance(data, str) else json.dumps(data)


class SpectacularSwaggerSplitView(SpectacularSwaggerView):
"""
Expand All @@ -127,8 +130,8 @@ def get(self, request, *args, **kwargs):
url=schema_url,
lang=request.GET.get('lang')
),
'settings': json.dumps(spectacular_settings.SWAGGER_UI_SETTINGS),
'oauth2_config': json.dumps(spectacular_settings.SWAGGER_UI_OAUTH2_CONFIG),
'settings': self._dump(spectacular_settings.SWAGGER_UI_SETTINGS),
'oauth2_config': self._dump(spectacular_settings.SWAGGER_UI_OAUTH2_CONFIG),
},
template_name=self.template_name_js,
content_type='application/javascript',
Expand Down
13 changes: 13 additions & 0 deletions tests/test_view.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from unittest import mock

import pytest
import yaml
from django.urls import path
Expand Down Expand Up @@ -112,3 +114,14 @@ def test_spectacular_swagger_ui_alternate(no_warnings):
response = APIClient().get('/api/v2/schema/swagger-ui-alt/?script=')
assert response.status_code == 200
assert b'"/api/v2/schema/"' in response.content


@mock.patch(
'drf_spectacular.settings.spectacular_settings.SWAGGER_UI_SETTINGS',
'{"deepLinking": true}'
)
@pytest.mark.urls(__name__)
def test_spectacular_ui_with_raw_settings(no_warnings):
response = APIClient().get('/api/v2/schema/swagger-ui/')
assert response.status_code == 200
assert b'const swagger_settings = {"deepLinking": true}\n\n' in response.content

0 comments on commit 0ed0b80

Please sign in to comment.