Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/api-guide/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ into the commonly used YAML-based OpenAPI format.
If your schema is static, you can use the `generateschema` management command:

```bash
./manage.py generateschema > openapi-schema.yml
./manage.py generateschema --file openapi-schema.yml
```

Once you've generated a schema in this way you can annotate it with any
Expand Down
8 changes: 7 additions & 1 deletion rest_framework/management/commands/generateschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def add_arguments(self, parser):
parser.add_argument('--format', dest="format", choices=['openapi', 'openapi-json'], default='openapi', type=str)
parser.add_argument('--urlconf', dest="urlconf", default=None, type=str)
parser.add_argument('--generator_class', dest="generator_class", default=None, type=str)
parser.add_argument('--file', dest="file", default=None, type=str)

def handle(self, *args, **options):
if options['generator_class']:
Expand All @@ -40,7 +41,12 @@ def handle(self, *args, **options):
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())

if options['file']:
with open(options['file'], 'wb') as f:
f.write(output)
else:
self.stdout.write(output.decode())

def get_renderer(self, format):
if self.get_mode() == COREAPI_MODE:
Expand Down
17 changes: 17 additions & 0 deletions tests/schemas/test_managementcommand.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import io
import os
import tempfile

import pytest
from django.conf.urls import url
Expand Down Expand Up @@ -73,6 +75,21 @@ def test_accepts_custom_schema_generator(self):
out_json = yaml.safe_load(self.out.getvalue())
assert out_json == CustomSchemaGenerator.SCHEMA

def test_writes_schema_to_file_on_parameter(self):
fd, path = tempfile.mkstemp()
try:
call_command('generateschema', '--file={}'.format(path), stdout=self.out)
# nothing on stdout
assert not self.out.getvalue()

call_command('generateschema', stdout=self.out)
expected_out = self.out.getvalue()
# file output identical to stdout output
with os.fdopen(fd) as fh:
assert expected_out and fh.read() == expected_out
finally:
os.remove(path)

@pytest.mark.skipif(yaml is None, reason='PyYAML is required.')
@override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'})
def test_coreapi_renders_default_schema_with_custom_title_url_and_description(self):
Expand Down