| 1 |
from django.core.management.base import BaseCommand |
| 2 |
from django.utils.module_loading import import_string |
| 3 |
|
| 4 |
from rest_framework import renderers |
| 5 |
from rest_framework.schemas.openapi import SchemaGenerator |
| 6 |
|
| 7 |
|
| 8 |
class Command(BaseCommand): |
| 9 |
help = "Generates configured API schema for project." |
| 10 |
|
| 11 |
def add_arguments(self, parser): |
| 12 |
parser.add_argument('--title', dest="title", default='', type=str) |
| 13 |
parser.add_argument('--url', dest="url", default=None, type=str) |
| 14 |
parser.add_argument('--description', dest="description", default=None, type=str) |
| 15 |
parser.add_argument('--format', dest="format", choices=['openapi', 'openapi-json'], default='openapi', type=str) |
| 16 |
parser.add_argument('--urlconf', dest="urlconf", default=None, type=str) |
| 17 |
parser.add_argument('--generator_class', dest="generator_class", default=None, type=str) |
| 18 |
parser.add_argument('--file', dest="file", default=None, type=str) |
| 19 |
parser.add_argument('--api_version', dest="api_version", default='', type=str) |
| 20 |
|
| 21 |
def handle(self, *args, **options): |
| 22 |
if options['generator_class']: |
| 23 |
generator_class = import_string(options['generator_class']) |
| 24 |
else: |
| 25 |
generator_class = SchemaGenerator |
| 26 |
generator = generator_class( |
| 27 |
url=options['url'], |
| 28 |
title=options['title'], |
| 29 |
description=options['description'], |
| 30 |
urlconf=options['urlconf'], |
| 31 |
version=options['api_version'], |
| 32 |
) |
| 33 |
schema = generator.get_schema(request=None, public=True) |
| 34 |
renderer = self.get_renderer(options['format']) |
| 35 |
output = renderer.render(schema, renderer_context={}) |
| 36 |
|
| 37 |
if options['file']: |
| 38 |
with open(options['file'], 'wb') as f: |
| 39 |
f.write(output) |
| 40 |
else: |
| 41 |
self.stdout.write(output.decode()) |
| 42 |
|
| 43 |
def get_renderer(self, format): |
| 44 |
renderer_cls = { |
| 45 |
'openapi': renderers.OpenAPIRenderer, |
| 46 |
'openapi-json': renderers.JSONOpenAPIRenderer, |
| 47 |
}[format] |
| 48 |
return renderer_cls() |