Repository navigation
Expand file tree
/
Copy pathexport_openapi_schema.py
More file actions
100 lines (84 loc) · 2.85 KB
/
Copy pathexport_openapi_schema.py
File metadata and controls
100 lines (84 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import json
from pathlib import Path
from typing import Any, Optional
from django.core.management.base import BaseCommand, CommandError, CommandParser
from django.urls.base import resolve
from django.utils.module_loading import import_string
from ninja.main import NinjaAPI
from ninja.management.utils import command_docstring
from ninja.responses import NinjaJSONEncoder
class Command(BaseCommand):
"""
Example:
```terminal
python manage.py export_openapi_schema
```
```terminal
python manage.py export_openapi_schema --api project.urls.api
```
"""
help = "Exports Open API schema"
def _get_api_instance(self, api_path: Optional[str] = None) -> NinjaAPI:
if not api_path:
try:
return resolve("/api/").func.keywords["api"] # type: ignore
except AttributeError:
raise CommandError(
"No NinjaAPI instance found; please specify one with --api"
) from None
try:
api = import_string(api_path)
except ImportError:
raise CommandError(
f"Module or attribute for {api_path} not found!"
) from None
if not isinstance(api, NinjaAPI):
raise CommandError(f"{api_path} is not instance of NinjaAPI!")
return api
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument(
"--api",
dest="api",
default=None,
type=str,
help="Specify api instance module",
)
parser.add_argument(
"--output",
dest="output",
default=None,
type=str,
help="Output schema to a file (outputs to stdout if omitted).",
)
parser.add_argument(
"--indent", dest="indent", default=None, type=int, help="JSON indent"
)
parser.add_argument(
"--sorted",
dest="sort_keys",
default=False,
action="store_true",
help="Sort Json keys",
)
parser.add_argument(
"--ensure-ascii",
dest="ensure_ascii",
default=False,
action="store_true",
help="ensure_ascii for JSON output",
)
def handle(self, *args: Any, **options: Any) -> None:
api = self._get_api_instance(options["api"])
schema = api.get_openapi_schema()
result = json.dumps(
schema,
cls=NinjaJSONEncoder,
indent=options["indent"],
sort_keys=options["sort_keys"],
ensure_ascii=options["ensure_ascii"],
)
if options["output"]:
Path(options["output"]).write_bytes(result.encode())
else:
self.stdout.write(result)
__doc__ = command_docstring(Command)