Skip to content

Commit

Permalink
suport config swagger-ui parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
PWZER committed Sep 27, 2021
1 parent 431c786 commit 819039b
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 37 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Only support Python3.
- [Falcon](https://falcon.readthedocs.io/en/stable/)
- [Bottle](https://bottlepy.org/docs/dev/)

> If you want to add supported frameworks, you can refer to [Flask Support](/swagger_ui/handlers/flask.py) or [Falcon Support](/swagger_ui/handlers/falcon.py), Implement the corresponding `handler` and `match` function.
## Usage

- Install
Expand Down Expand Up @@ -99,6 +101,24 @@ Only support Python3.

Open `http://<host>:<port>/api/doc` view api doc.

## SwaggerUI Configuration

You can configure Swagger parameters using the dictionary, Both key and value are of type str, if value is JavaScript string, you need to wrap the quotes around it.
Such as `"layout": "\"StandaloneLayout\""`.

```python
parameters = {
"deepLinking": "true",
"displayRequestDuration": "true",
"layout": "\"StandaloneLayout\"",
"plugins": "[SwaggerUIBundle.plugins.DownloadUrl]",
"presets": "[SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]",
}
api_doc(app, config_path='./config/test.yaml', parameters=parameters)
```

For details about configuration parameters, see the official documentation [Configuration](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).

## Swagger UI
Swagger UI version is `v3.52.3`. see [https://github.com/swagger-api/swagger-ui](https://github.com/swagger-api/swagger-ui).

Expand Down
24 changes: 22 additions & 2 deletions swagger_ui/core.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import copy
import importlib
import re
import urllib.request
Expand All @@ -10,6 +11,16 @@
from swagger_ui.handlers import supported_list


_DefaultSwaggerUIBundleParameters = {
"dom_id": "\"#swagger-ui\"",
"deepLinking": "true",
"displayRequestDuration": "true",
"layout": "\"StandaloneLayout\"",
"plugins": "[SwaggerUIBundle.plugins.DownloadUrl]",
"presets": "[SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]",
}


class ApplicationDocument(object):

def __init__(self,
Expand All @@ -22,6 +33,7 @@ def __init__(self,
url_prefix=r'/api/doc',
title='API doc',
editor=False,
parameters={},
**extra_config):
self.app = app
self.app_type = app_type
Expand All @@ -37,6 +49,12 @@ def __init__(self,
assert self.config or self.config_url or self.config_path or self.config_spec, \
'One of arguments "config", "config_path", "config_url" or "config_spec" is required!'

# parameters
self.parameters = copy.deepcopy(_DefaultSwaggerUIBundleParameters)
if parameters:
self.parameters.update(parameters)
self.parameters["url"] = "\"{}\"".format(self.swagger_json_uri_absolute)

self.env = Environment(
loader=FileSystemLoader(
str(SWAGGER_UI_PY_ROOT.joinpath('templates'))),
Expand All @@ -52,15 +70,17 @@ def doc_html(self):
return self.env.get_template('doc.html').render(
url_prefix=self.url_prefix,
title=self.title,
config_url=self.uri(r'/swagger.json')
config_url=self.swagger_json_uri_absolute,
parameters=self.parameters,
)

@property
def editor_html(self):
return self.env.get_template('editor.html').render(
url_prefix=self.url_prefix,
title=self.title,
config_url=self.uri(r'/swagger.json')
config_url=self.swagger_json_uri_absolute,
parameters=self.parameters,
)

def uri(self, suffix=''):
Expand Down
16 changes: 4 additions & 12 deletions swagger_ui/templates/doc.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,10 @@
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "{{ config_url }}",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
{%- for key, value in parameters.items() %}
{{ key|safe }}: {{ value|safe }},
{%- endfor %}
});
// End Swagger UI call region

window.ui = ui;
Expand Down
66 changes: 43 additions & 23 deletions tools/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@
import requests

parser = argparse.ArgumentParser()
parser.add_argument('--ui', action='store_true', help='Enabled to update swagger ui.')
parser.add_argument('--editor', action='store_true', help='Enabled to update swagger editor.')
parser.add_argument('--ui', action='store_true',
help='Enabled to update swagger ui.')
parser.add_argument('--editor', action='store_true',
help='Enabled to update swagger editor.')
parser.add_argument('--ui-version', type=str, default=None,
help='Specify the version of swagger ui, Default latest version.')
parser.add_argument('--editor-version', type=str, default=None,
help='Specify the version of swagger editor, Default latest version.')
parser.add_argument('--no-clean', action='store_true',
help='disable auto clean the temporary files.')
cmd_args = parser.parse_args()


Expand Down Expand Up @@ -52,15 +56,17 @@ def download_archive(repo, version):
if version is None:
version = detect_latest_release(repo)

file_name = '{}.tar.gz'.format(version)
file_name = '{}-{}.tar.gz'.format(repo.split('/')[1], version)
save_path = cur_dir.joinpath(file_name)
archive_url = 'https://github.com/{}/archive/{}'.format(repo, file_name)

print('archive downloading: {}'.format(archive_url))
with requests.get(archive_url, stream=True) as resp:
assert resp.status_code == 200
with save_path.open('wb') as out:
shutil.copyfileobj(resp.raw, out)
if not (cmd_args.no_clean and save_path.exists()):
archive_url = 'https://github.com/{}/archive/{}'.format(repo, file_name)
print('archive downloading: {}'.format(archive_url))
with requests.get(archive_url, stream=True) as resp:
assert resp.status_code == 200
with save_path.open('wb') as out:
shutil.copyfileobj(resp.raw, out)
print('archive download completed: {}'.format(save_path))

print('open tarfile: {}'.format(file_name))
tar_file = tarfile.open(save_path)
Expand All @@ -69,28 +75,42 @@ def download_archive(repo, version):

dist_copy(repo, swagger_ui_dir.joinpath('dist'))

print('remove {}'.format(swagger_ui_dir))
shutil.rmtree(swagger_ui_dir)
if not cmd_args.no_clean:
print('remove {}'.format(swagger_ui_dir))
shutil.rmtree(swagger_ui_dir)

print('remove {}'.format(save_path))
save_path.unlink()
print('remove {}'.format(save_path))
save_path.unlink()

print('Successed')


def replace_html_content():
for html_path in templates_dir.glob('**/*.html'):
with html_path.open('r') as html_file:
index_content = html_file.read()

index_content = re.sub('<title>.*</title>', '<title> {{ title }} </title>', index_content)
index_content = re.sub('src="\\.(/dist)', 'src="{{ url_prefix }}/static', index_content)
index_content = re.sub('href="\\.(/dist)', 'href="{{ url_prefix }}/static', index_content)
index_content = re.sub('src="\\.', 'src="{{ url_prefix }}/static', index_content)
index_content = re.sub('href="\\.', 'href="{{ url_prefix }}/static', index_content)
index_content = re.sub('https://petstore.swagger.io/v[1-9]/swagger.json',
'{{ config_url }}', index_content)
html_content = html_file.read()

html_content = re.sub(r'<title>.*</title>', '<title> {{ title }} </title>', html_content)
html_content = re.sub(r'src="\.(/dist)', 'src="{{ url_prefix }}/static', html_content)
html_content = re.sub(r'href="\.(/dist)', 'href="{{ url_prefix }}/static', html_content)
html_content = re.sub(r'src="\.', 'src="{{ url_prefix }}/static', html_content)
html_content = re.sub(r'href="\.', 'href="{{ url_prefix }}/static', html_content)
html_content = re.sub(r'https://petstore.swagger.io/v[1-9]/swagger.json',
'{{ config_url }}', html_content)

if str(html_path).endswith('doc.html'):
html_content = re.sub(r'https://petstore.swagger.io/v[1-9]/swagger.json',
'{{ config_url }}', html_content)
content = '''const ui = SwaggerUIBundle({
{%- for key, value in parameters.items() %}
{{ key|safe }}: {{ value|safe }},
{%- endfor %}
});'''
html_content = re.sub(r'const ui = SwaggerUIBundle\({.*}\);$', content,
html_content, flags=re.MULTILINE | re.DOTALL)

with html_path.open('w') as html_file:
html_file.write(index_content)
html_file.write(html_content)


if __name__ == '__main__':
Expand Down

0 comments on commit 819039b

Please sign in to comment.