django-rest-framework/rest_framework/management/commands/generateschema.py
Tom Christie 8908934928
Add OpenAPIRenderer and generate_schema management command. (#6229)
* Add OpenAPIRenderer and generate_schema command

* Add both OpenAPIRenderer and JSONOpenAPIRenderer

* Add flags to generate_schema command

* Fix syntax error

* Pull coreschema references into method, so they are only used if 'OpenAPIRenderer' is in use.

* generate_schema -> generateschema, and fix to OpenAPIRenderer

* Ensure that renderers generate bytes and generateschema outputs text

* Drop unused import
2018-10-03 15:28:04 +01:00

40 lines
1.4 KiB
Python

from django.core.management.base import BaseCommand
from rest_framework.compat import coreapi
from rest_framework.renderers import (
CoreJSONRenderer, JSONOpenAPIRenderer, OpenAPIRenderer
)
from rest_framework.schemas.generators import SchemaGenerator
class Command(BaseCommand):
help = "Generates configured API schema for project."
def add_arguments(self, parser):
parser.add_argument('--title', dest="title", default=None, type=str)
parser.add_argument('--url', dest="url", default=None, type=str)
parser.add_argument('--description', dest="description", default=None, type=str)
parser.add_argument('--format', dest="format", choices=['openapi', 'openapi-json', 'corejson'], default='openapi', type=str)
def handle(self, *args, **options):
assert coreapi is not None, 'coreapi must be installed.'
generator = SchemaGenerator(
url=options['url'],
title=options['title'],
description=options['description']
)
schema = generator.get_schema(request=None, public=True)
renderer = self.get_renderer(options['format'])
output = renderer.render(schema, renderer_context={})
self.stdout.write(output.decode('utf-8'))
def get_renderer(self, format):
return {
'corejson': CoreJSONRenderer(),
'openapi': OpenAPIRenderer(),
'openapi-json': JSONOpenAPIRenderer()
}[format]