graphene-django/graphene_django/management/commands/graphql_schema.py

73 lines
2.1 KiB
Python
Raw Normal View History

import importlib
import json
from django.core.management.base import BaseCommand, CommandError
from graphene_django.settings import graphene_settings
2017-12-18 20:02:04 +03:00
2017-12-10 08:53:13 +03:00
class CommandArguments(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
2018-07-20 02:51:33 +03:00
"--schema",
2017-12-10 08:53:13 +03:00
type=str,
2018-07-20 02:51:33 +03:00
dest="schema",
2017-12-10 08:53:13 +03:00
default=graphene_settings.SCHEMA,
2018-07-20 02:51:33 +03:00
help="Django app containing schema to dump, e.g. myproject.core.schema.schema",
)
2017-12-10 08:53:13 +03:00
parser.add_argument(
2018-07-20 02:51:33 +03:00
"--out",
2017-12-10 08:53:13 +03:00
type=str,
2018-07-20 02:51:33 +03:00
dest="out",
2017-12-10 08:53:13 +03:00
default=graphene_settings.SCHEMA_OUTPUT,
2018-07-20 02:51:33 +03:00
help="Output file (default: schema.json)",
)
2017-12-10 08:53:13 +03:00
parser.add_argument(
2018-07-20 02:51:33 +03:00
"--indent",
2017-12-10 08:53:13 +03:00
type=int,
2018-07-20 02:51:33 +03:00
dest="indent",
2017-12-10 08:53:13 +03:00
default=graphene_settings.SCHEMA_INDENT,
2018-07-20 02:51:33 +03:00
help="Output file indent (default: None)",
)
class Command(CommandArguments):
2018-07-20 02:51:33 +03:00
help = "Dump Graphene schema JSON to file"
can_import_settings = True
def save_file(self, out, schema_dict, indent):
2018-07-20 02:51:33 +03:00
with open(out, "w") as outfile:
json.dump(schema_dict, outfile, indent=indent)
def handle(self, *args, **options):
2018-07-20 02:51:33 +03:00
options_schema = options.get("schema")
if options_schema and type(options_schema) is str:
2018-07-20 02:51:33 +03:00
module_str, schema_name = options_schema.rsplit(".", 1)
mod = importlib.import_module(module_str)
schema = getattr(mod, schema_name)
elif options_schema:
schema = options_schema
else:
schema = graphene_settings.SCHEMA
2018-07-20 02:51:33 +03:00
out = options.get("out") or graphene_settings.SCHEMA_OUTPUT
if not schema:
2018-07-20 02:51:33 +03:00
raise CommandError(
"Specify schema on GRAPHENE.SCHEMA setting or by using --schema"
)
2018-07-20 02:51:33 +03:00
indent = options.get("indent")
schema_dict = {"data": schema.introspect()}
self.save_file(out, schema_dict, indent)
2018-07-20 02:51:33 +03:00
style = getattr(self, "style", None)
success = getattr(style, "SUCCESS", lambda x: x)
2018-07-20 02:51:33 +03:00
self.stdout.write(success("Successfully dumped GraphQL schema to %s" % out))