explict imports from graphene

This commit is contained in:
Dave A 2019-06-09 10:43:03 -04:00
parent abe58cc40e
commit ab25d0770a
3 changed files with 98 additions and 69 deletions

View File

@ -9,7 +9,9 @@ For executing a query a schema, you can directly call the ``execute`` method on
.. code:: python .. code:: python
schema = graphene.Schema(...) from graphene import Schema
schema = Schema(...)
result = schema.execute('{ name }') result = schema.execute('{ name }')
``result`` represents the result of execution. ``result.data`` is the result of executing the query, ``result.errors`` is ``None`` if no errors occurred, and is a non-empty list if an error occurred. ``result`` represents the result of execution. ``result.data`` is the result of executing the query, ``result.errors`` is ``None`` if no errors occurred, and is a non-empty list if an error occurred.
@ -25,15 +27,17 @@ You can pass context to a query via ``context``.
.. code:: python .. code:: python
class Query(graphene.ObjectType): from graphene import ObjectType, String, Schema
name = graphene.String()
class Query(ObjectType):
name = String()
def resolve_name(root, info): def resolve_name(root, info):
return info.context.get('name') return info.context.get('name')
schema = graphene.Schema(Query) schema = Schema(Query)
result = schema.execute('{ name }', context={'name': 'Syrus'}) result = schema.execute('{ name }', context={'name': 'Syrus'})
assert result.data['name'] == 'Syrus'
Variables Variables
@ -44,13 +48,15 @@ You can pass variables to a query via ``variables``.
.. code:: python .. code:: python
class Query(graphene.ObjectType): from graphene import ObjectType, Field, ID, Schema
user = graphene.Field(User, id=graphene.ID(required=True))
class Query(ObjectType):
user = Field(User, id=ID(required=True))
def resolve_user(root, info, id): def resolve_user(root, info, id):
return get_user_by_id(id) return get_user_by_id(id)
schema = graphene.Schema(Query) schema = Schema(Query)
result = schema.execute( result = schema.execute(
''' '''
query getUser($id: ID) { query getUser($id: ID) {
@ -71,13 +77,15 @@ Value used for :ref:`ResolverRootArgument` in root queries and mutations can be
.. code:: python .. code:: python
class Query(graphene.ObjectType): from graphene import ObjectType, Field, Schema
me = graphene.Field(User)
class Query(ObjectType):
me = Field(User)
def resolve_user(root, info): def resolve_user(root, info):
return get_user_by_id(root.id) return {'id': root.id, 'firstName': root.name}
schema = graphene.Schema(Query) schema = Schema(Query)
user_root = User(id=12, name='bob'} user_root = User(id=12, name='bob'}
result = schema.execute( result = schema.execute(
''' '''
@ -91,6 +99,7 @@ Value used for :ref:`ResolverRootArgument` in root queries and mutations can be
''', ''',
root=user_root root=user_root
) )
assert result.data['user']['id'] == user_root.id
Operation Name Operation Name
______________ ______________
@ -99,13 +108,15 @@ If there are multiple operations defined in a query string, ``operation_name`` s
.. code:: python .. code:: python
class Query(graphene.ObjectType): from graphene import ObjectType, Field, Schema
me = graphene.Field(User)
class Query(ObjectType):
me = Field(User)
def resolve_user(root, info): def resolve_user(root, info):
return get_user_by_id(12) return get_user_by_id(12)
schema = graphene.Schema(Query) schema = Schema(Query)
query_string = ''' query_string = '''
query getUserWithFirstName { query getUserWithFirstName {
user { user {
@ -117,8 +128,7 @@ If there are multiple operations defined in a query string, ``operation_name`` s
query getUserWithFullName { query getUserWithFullName {
user { user {
id id
firstName fullName
lastName
} }
} }
''' '''
@ -126,3 +136,4 @@ If there are multiple operations defined in a query string, ``operation_name`` s
query_string, query_string,
operation_name='getUserWithFullName' operation_name='getUserWithFullName'
) )
assert result.data['user']['fullName']

View File

@ -76,12 +76,12 @@ In Graphene, we can define a simple schema using the following code:
.. code:: python .. code:: python
import graphene from graphene import ObjectType, String, Schema
class Query(graphene.ObjectType): class Query(ObjectType):
# this defines a Field `hello` in our Schema with a single Argument `name` # this defines a Field `hello` in our Schema with a single Argument `name`
hello = graphene.String(name=graphene.String(default_value="stranger")) hello = String(name=String(default_value="stranger"))
goodbye = graphene.String() goodbye = String()
# our Resolver method takes the GraphQL context (root, info) as well as # our Resolver method takes the GraphQL context (root, info) as well as
# Argument (name) for the Field and returns data for the query Response # Argument (name) for the Field and returns data for the query Response
@ -91,7 +91,7 @@ In Graphene, we can define a simple schema using the following code:
def resolve_goodbye(root, info): def resolve_goodbye(root, info):
return 'See ya!' return 'See ya!'
schema = graphene.Schema(query=Query) schema = Schema(query=Query)
A GraphQL **Schema** describes each **Field** in the data model provided by the server using scalar types like *String*, *Int* and *Enum* and compound types like *List* and *Object*. For more details refer to the Graphene :ref:`TypesReference`. A GraphQL **Schema** describes each **Field** in the data model provided by the server using scalar types like *String*, *Int* and *Enum* and compound types like *List* and *Object*. For more details refer to the Graphene :ref:`TypesReference`.

View File

@ -18,13 +18,15 @@ This example model defines a Person, with a first and a last name:
.. code:: python .. code:: python
class Person(graphene.ObjectType): from graphene import ObjectType, String
first_name = graphene.String()
last_name = graphene.String() class Person(ObjectType):
full_name = graphene.String() first_name = String()
last_name = String()
full_name = String()
def resolve_full_name(parent, info): def resolve_full_name(parent, info):
return f'{parent.first_name} {parent.last_name}' return f"{parent.first_name} {parent.last_name}"
This *ObjectType* defines the feild **first\_name**, **last\_name**, and **full\_name**. Each field is specified as a class attribute, and each attribute maps to a Field. Data is fetched by our ``resolve_full_name`` :ref:`resolver method<Resolvers>` for ``full_name`` field and the :ref:`DefaultResolver` for other fields. This *ObjectType* defines the feild **first\_name**, **last\_name**, and **full\_name**. Each field is specified as a class attribute, and each attribute maps to a Field. Data is fetched by our ``resolve_full_name`` :ref:`resolver method<Resolvers>` for ``full_name`` field and the :ref:`DefaultResolver` for other fields.
@ -56,8 +58,8 @@ Each resolver method takes the parameters:
.. _ResolverArguments: .. _ResolverArguments:
Resolver Arguments Resolver Parameters
~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
.. _ResolverRootArgument: .. _ResolverRootArgument:
@ -75,20 +77,20 @@ If we have a schema with Person type and one field on the root query.
.. code:: python .. code:: python
import graphene from graphene import ObjectType, String, Field
class Person(graphene.ObjectType): class Person(ObjectType):
full_name = graphene.String() full_name = String()
def resolve_full_name(parent, info): def resolve_full_name(parent, info):
return f'{parent.first_name} {parent.last_name}' return f"{parent.first_name} {parent.last_name}"
class Query(graphene.ObjectType): class Query(ObjectType):
me = graphene.Field(Person) me = Field(Person)
def resolve_me(parent, info): def resolve_me(parent, info):
# returns an object that represents a Person # returns an object that represents a Person
return get_human(name='Luke Skywalker') return get_human(name="Luke Skywalker")
When we execute a query against that schema. When we execute a query against that schema.
@ -137,10 +139,10 @@ keyword arguments. For example:
.. code:: python .. code:: python
import graphene from graphene import ObjectType, Field, String
class Query(graphene.ObjectType): class Query(ObjectType):
human_by_name = graphene.Field(Human, name=graphene.String(required=True)) human_by_name = Field(Human, name=String(required=True))
def resolve_human_by_name(parent, info, name): def resolve_human_by_name(parent, info, name):
return get_human(name=name) return get_human(name=name)
@ -170,9 +172,11 @@ The two resolvers in this example are effectively the same.
.. code:: python .. code:: python
class Person(graphene.ObjectType): from graphene import ObjectType, String
first_name = graphene.String()
last_name = graphene.String() class Person(ObjectType):
first_name = String()
last_name = String()
@staticmethod @staticmethod
def resolve_first_name(parent, info): def resolve_first_name(parent, info):
@ -206,15 +210,17 @@ If the :ref:`ResolverRootArgument` is a dictionary, the resolver will look for a
from collections import namedtuple from collections import namedtuple
from graphene import ObjectType, String, Field, Schema
PersonValueObject = namedtuple('Person', 'first_name', 'last_name') PersonValueObject = namedtuple('Person', 'first_name', 'last_name')
class Person(graphene.ObjectType): class Person(ObjectType):
first_name = graphene.String() first_name = String()
last_name = graphene.String() last_name = String()
class Query(graphene.Object): class Query(ObjectType):
me = graphene.Field(Person) me = Field(Person)
my_best_friend = graphene.Field(Person) my_best_friend = Field(Person)
def resolve_me(parent, info): def resolve_me(parent, info):
# always pass an object for `me` field # always pass an object for `me` field
@ -224,7 +230,7 @@ If the :ref:`ResolverRootArgument` is a dictionary, the resolver will look for a
# always pass a dictionary for `my_best_fiend_field` # always pass a dictionary for `my_best_fiend_field`
return {"first_name": "R2", "last_name": "D2"} return {"first_name": "R2", "last_name": "D2"}
schema = graphene.Schema(query=Query) schema = Schema(query=Query)
result = schema.execute(''' result = schema.execute('''
{ {
me { firstName lastName } me { firstName lastName }
@ -252,10 +258,10 @@ For example, given this schema:
.. code:: python .. code:: python
import graphene from graphene import ObjectType, String
class Query(graphene.ObjectType): class Query(ObjectType):
hello = graphene.String(required=True, name=graphene.String()) hello = String(required=True, name=String())
def resolve_hello(parent, info, name): def resolve_hello(parent, info, name):
return name if name else 'World' return name if name else 'World'
@ -279,8 +285,10 @@ into a dict:
.. code:: python .. code:: python
class Query(graphene.ObjectType): from graphene import ObjectType, String
hello = graphene.String(required=True, name=graphene.String())
class Query(ObjectType):
hello = String(required=True, name=String())
def resolve_hello(parent, info, **kwargs): def resolve_hello(parent, info, **kwargs):
name = kwargs.get('name', 'World') name = kwargs.get('name', 'World')
@ -290,8 +298,10 @@ Or by setting a default value for the keyword argument:
.. code:: python .. code:: python
class Query(graphene.ObjectType): from graphene import ObjectType, String
hello = graphene.String(required=True, name=graphene.String())
class Query(ObjectType):
hello = String(required=True, name=String())
def resolve_hello(parent, info, name='World'): def resolve_hello(parent, info, name='World'):
return f'Hello, {name}!' return f'Hello, {name}!'
@ -300,10 +310,12 @@ One can also set a default value for an Argument in the GraphQL schema itself us
.. code:: python .. code:: python
class Query(graphene.ObjectType): from graphene import ObjectType, String
hello = graphene.String(
class Query(ObjectType):
hello = String(
required=True, required=True,
name=graphene.Argument(graphene.String, default_value='World') name=String(default_value='World')
) )
def resolve_hello(parent, info, name): def resolve_hello(parent, info, name):
@ -316,15 +328,15 @@ A field can use a custom resolver from outside the class:
.. code:: python .. code:: python
import graphene from graphene import ObjectType, String
def resolve_full_name(person, info): def resolve_full_name(person, info):
return '{} {}'.format(person.first_name, person.last_name) return '{} {}'.format(person.first_name, person.last_name)
class Person(graphene.ObjectType): class Person(ObjectType):
first_name = graphene.String() first_name = String()
last_name = graphene.String() last_name = String()
full_name = graphene.String(resolver=resolve_full_name) full_name = String(resolver=resolve_full_name)
Instances as value objects Instances as value objects
@ -359,7 +371,9 @@ property on the ``Meta`` class:
.. code:: python .. code:: python
class MyGraphQlSong(graphene.ObjectType): from graphene import ObjectType
class MyGraphQlSong(ObjectType):
class Meta: class Meta:
name = 'Song' name = 'Song'
@ -370,7 +384,9 @@ The schema description of an *ObjectType* can be set as a docstring on the Pytho
.. code:: python .. code:: python
class MyGraphQlSong(graphene.ObjectType): from graphene import ObjectType
class MyGraphQlSong(ObjectType):
''' We can set the schema description for an Object Type here on a docstring ''' ''' We can set the schema description for an Object Type here on a docstring '''
class Meta: class Meta:
description = 'But if we set the description in Meta, this value is used instead' description = 'But if we set the description in Meta, this value is used instead'
@ -386,9 +402,11 @@ See :ref:`Interfaces` for more information.
.. code:: python .. code:: python
from graphene import ObjectType
Song = namedtuple('Song', ('title', 'artist')) Song = namedtuple('Song', ('title', 'artist'))
class MyGraphQlSong(graphene.ObjectType): class MyGraphQlSong(ObjectType):
class Meta: class Meta:
interfaces = (graphene.Node, ) interfaces = (graphene.Node, )
possible_types = (Song, ) possible_types = (Song, )