Skip to content

Commit 3aa929f

Browse files
committed
Moved django-graphql-view and django-graphiql into graphene-django 😎
1 parent a4306c8 commit 3aa929f

File tree

14 files changed

+1025
-74
lines changed

14 files changed

+1025
-74
lines changed

.gitignore

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -59,20 +59,6 @@ docs/_build/
5959
# PyBuilder
6060
target/
6161

62-
63-
/tests/django.sqlite
64-
65-
/graphene/index.json
66-
/graphene/meta.json
67-
68-
/meta.json
69-
/index.json
70-
71-
/docs/playground/graphene-js/pypyjs-release-nojit/
72-
/docs/static/playground/lib
73-
74-
/docs/static/playground
75-
7662
# PyCharm
7763
.idea
7864

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,33 @@ For instaling graphene, just run this command in your shell
1616
pip install "graphene-django>=1.0.dev"
1717
```
1818

19+
### Settings
20+
21+
```python
22+
INSTALLED_APPS = (
23+
# ...
24+
'graphene_django',
25+
)
26+
27+
GRAPHENE = {
28+
'SCHEMA': 'app.schema.schema' # Where your Graphene schema lives
29+
}
30+
```
31+
32+
### Urls
33+
34+
We need to set up a `GraphQL` endpoint in our Django app, so we can serve the queries.
35+
36+
```python
37+
from django.conf.urls import url
38+
from graphene_django.views import GraphQLView
39+
40+
urlpatterns = [
41+
# ...
42+
url(r'^graphql', GraphQLView.as_view(graphiql=True)),
43+
]
44+
```
45+
1946
## Examples
2047

2148
Here is a simple Django model:

README.rst

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,36 @@ For instaling graphene, just run this command in your shell
2020
2121
pip install "graphene-django>=1.0.dev"
2222
23+
Settings
24+
~~~~~~~~
25+
26+
.. code:: python
27+
28+
INSTALLED_APPS = (
29+
# ...
30+
'graphene_django',
31+
)
32+
33+
GRAPHENE = {
34+
'SCHEMA': 'app.schema.schema' # Where your Graphene schema lives
35+
}
36+
37+
Urls
38+
~~~~
39+
40+
We need to set up a ``GraphQL`` endpoint in our Django app, so we can
41+
serve the queries.
42+
43+
.. code:: python
44+
45+
from django.conf.urls import url
46+
from graphene_django.views import GraphQLView
47+
48+
urlpatterns = [
49+
# ...
50+
url(r'^graphql', GraphQLView.as_view(graphiql=True)),
51+
]
52+
2353
Examples
2454
--------
2555

django_test_settings.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,17 @@
1818
'NAME': 'django_test.sqlite',
1919
}
2020
}
21+
22+
TEMPLATES = [
23+
{
24+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
25+
'DIRS': [],
26+
'APP_DIRS': True,
27+
},
28+
]
29+
30+
GRAPHENE = {
31+
'SCHEMA': 'graphene_django.tests.schema_view.schema'
32+
}
33+
34+
ROOT_URLCONF = 'graphene_django.tests.urls'

examples/cookbook/cookbook/settings.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
'django.contrib.sessions',
3838
'django.contrib.messages',
3939
'django.contrib.staticfiles',
40-
'django_graphiql',
40+
'graphene_django',
4141

4242
'cookbook.ingredients.apps.IngredientsConfig',
4343
'cookbook.recipes.apps.RecipesConfig',
@@ -54,6 +54,10 @@
5454
'django.middleware.clickjacking.XFrameOptionsMiddleware',
5555
]
5656

57+
GRAPHENE = {
58+
'SCHEMA': 'cookbook.schema.schema'
59+
}
60+
5761
ROOT_URLCONF = 'cookbook.urls'
5862

5963
TEMPLATES = [

examples/cookbook/cookbook/urls.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
from django.conf.urls import include, url
22
from django.contrib import admin
3-
from django.views.decorators.csrf import csrf_exempt
43

54
from cookbook.schema import schema
65
from graphene_django.views import GraphQLView
76

87
urlpatterns = [
98
url(r'^admin/', admin.site.urls),
10-
url(r'^graphql', csrf_exempt(GraphQLView.as_view(schema=schema))),
11-
url(r'^graphiql', include('django_graphiql.urls')),
9+
url(r'^graphql', GraphQLView.as_view(graphiql=True)),
1210
]

graphene_django/management/commands/graphql_schema.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
from django import get_version as get_django_version
77
from django.core.management.base import BaseCommand, CommandError
88

9+
from graphene_django.settings import graphene_settings
10+
911
LT_DJANGO_1_8 = StrictVersion(get_django_version()) < StrictVersion('1.8')
1012

1113
if LT_DJANGO_1_8:
@@ -16,7 +18,7 @@ class CommandArguments(BaseCommand):
1618
type=str,
1719
dest='schema',
1820
default='',
19-
help='Django app containing schema to dump, e.g. myproject.core.schema',
21+
help='Django app containing schema to dump, e.g. myproject.core.schema.schema',
2022
),
2123
make_option(
2224
'--out',
@@ -35,14 +37,14 @@ def add_arguments(self, parser):
3537
'--schema',
3638
type=str,
3739
dest='schema',
38-
default=getattr(settings, 'GRAPHENE_SCHEMA', ''),
39-
help='Django app containing schema to dump, e.g. myproject.core.schema')
40+
default=graphene_settings.SCHEMA,
41+
help='Django app containing schema to dump, e.g. myproject.core.schema.schema')
4042

4143
parser.add_argument(
4244
'--out',
4345
type=str,
4446
dest='out',
45-
default=getattr(settings, 'GRAPHENE_SCHEMA_OUTPUT', 'schema.json'),
47+
default=graphene_settings.SCHEMA_OUTPUT,
4648
help='Output file (default: schema.json)')
4749

4850

@@ -56,14 +58,18 @@ def save_file(self, out, schema_dict):
5658

5759
def handle(self, *args, **options):
5860
from django.conf import settings
59-
schema = options.get('schema') or getattr(settings, 'GRAPHENE_SCHEMA', '')
60-
out = options.get('out') or getattr(settings, 'GRAPHENE_SCHEMA_OUTPUT', 'schema.json')
61+
options_schema = options.get('schema')
62+
if options_schema:
63+
schema = importlib.import_module(options_schema)
64+
else:
65+
schema = graphene_settings.SCHEMA
66+
67+
out = options.get('out') or graphene_settings.SCHEMA_OUTPUT
6168

62-
if schema == '':
63-
raise CommandError('Specify schema on GRAPHENE_SCHEMA setting or by using --schema')
64-
i = importlib.import_module(schema)
69+
if not schema:
70+
raise CommandError('Specify schema on GRAPHENE.SCHEMA setting or by using --schema')
6571

66-
schema_dict = {'data': i.schema.introspect()}
72+
schema_dict = {'data': schema.introspect()}
6773
self.save_file(out, schema_dict)
6874

6975
style = getattr(self, 'style', None)

graphene_django/settings.py

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""
2+
Settings for Graphene are all namespaced in the GRAPHENE setting.
3+
For example your project's `settings.py` file might look like this:
4+
GRAPHENE = {
5+
'SCHEMA': 'my_app.schema.schema'
6+
'MIDDLEWARE': (
7+
'graphene_django.debug.DjangoDebugMiddleware',
8+
)
9+
}
10+
This module provides the `graphene_settings` object, that is used to access
11+
Graphene settings, checking for user settings first, then falling
12+
back to the defaults.
13+
"""
14+
from __future__ import unicode_literals
15+
16+
from django.conf import settings
17+
from django.test.signals import setting_changed
18+
from django.utils import six
19+
20+
try:
21+
import importlib # Available in Python 3.1+
22+
except ImportError:
23+
from django.utils import importlib # Will be removed in Django 1.9
24+
25+
26+
# Copied shamelessly from Django REST Framework
27+
28+
DEFAULTS = {
29+
'SCHEMA': None,
30+
'SCHEMA_OUTPUT': 'schema.json',
31+
'MIDDLEWARE': (),
32+
}
33+
34+
if settings.DEBUG:
35+
DEFAULTS['MIDDLEWARE'] += (
36+
'graphene_django.debug.DjangoDebugMiddleware',
37+
)
38+
39+
# List of settings that may be in string import notation.
40+
IMPORT_STRINGS = (
41+
'MIDDLEWARE',
42+
'SCHEMA',
43+
)
44+
45+
46+
47+
def perform_import(val, setting_name):
48+
"""
49+
If the given setting is a string import notation,
50+
then perform the necessary import or imports.
51+
"""
52+
if val is None:
53+
return None
54+
elif isinstance(val, six.string_types):
55+
return import_from_string(val, setting_name)
56+
elif isinstance(val, (list, tuple)):
57+
return [import_from_string(item, setting_name) for item in val]
58+
return val
59+
60+
61+
def import_from_string(val, setting_name):
62+
"""
63+
Attempt to import a class from a string representation.
64+
"""
65+
try:
66+
# Nod to tastypie's use of importlib.
67+
parts = val.split('.')
68+
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
69+
module = importlib.import_module(module_path)
70+
return getattr(module, class_name)
71+
except (ImportError, AttributeError) as e:
72+
msg = "Could not import '%s' for Graphene setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
73+
raise ImportError(msg)
74+
75+
76+
class GrapheneSettings(object):
77+
"""
78+
A settings object, that allows API settings to be accessed as properties.
79+
For example:
80+
from graphene_django.settings import settings
81+
print(settings.SCHEMA)
82+
Any setting with string import paths will be automatically resolved
83+
and return the class, rather than the string literal.
84+
"""
85+
def __init__(self, user_settings=None, defaults=None, import_strings=None):
86+
if user_settings:
87+
self._user_settings = user_settings
88+
self.defaults = defaults or DEFAULTS
89+
self.import_strings = import_strings or IMPORT_STRINGS
90+
91+
@property
92+
def user_settings(self):
93+
if not hasattr(self, '_user_settings'):
94+
self._user_settings = getattr(settings, 'GRAPHENE', {})
95+
return self._user_settings
96+
97+
def __getattr__(self, attr):
98+
if attr not in self.defaults:
99+
raise AttributeError("Invalid Graphene setting: '%s'" % attr)
100+
101+
try:
102+
# Check if present in user settings
103+
val = self.user_settings[attr]
104+
except KeyError:
105+
# Fall back to defaults
106+
val = self.defaults[attr]
107+
108+
# Coerce import strings into classes
109+
if attr in self.import_strings:
110+
val = perform_import(val, attr)
111+
112+
# Cache the result
113+
setattr(self, attr, val)
114+
return val
115+
116+
117+
graphene_settings = GrapheneSettings(None, DEFAULTS, IMPORT_STRINGS)
118+
119+
120+
def reload_graphene_settings(*args, **kwargs):
121+
global graphene_settings
122+
setting, value = kwargs['setting'], kwargs['value']
123+
if setting == 'GRAPHENE':
124+
graphene_settings = GrapheneSettings(value, DEFAULTS, IMPORT_STRINGS)
125+
126+
127+
setting_changed.connect(reload_graphene_settings)

0 commit comments

Comments
 (0)