py_gql.execution#

class py_gql.execution.AsyncIOExecutor(*args, execute_blocking_resolvers_in_thread=True, **kwargs)[source]#

Executor implementation to work Python’s asyncio.

supports_subscriptions = True#
static ensure_wrapped(value)[source]#

Ensure values are wrapped in the necessary container type.

This is essentially used after execution has finished to make sure the final value conforms to the expected types (e.g. coroutines) and avoid consumers having to typecheck them needlessly.

static gather_values(values)[source]#

Group multiple wrapped values inside a single wrapped value.

This is equivalent to the asyncio.gather semantics.

static map_value(value, then, else_=None)[source]#

Execute a callback on a wrapped value, potentially catching exceptions.

This is used internally to orchestrate callbacks and should be treated similarly to await semantics the map in Future combinators.

static unwrap_value(value)[source]#

Recursively traverse wrapped values.

Given that resolution across the graph can span multiple level, this is used to support resolved values depending on deeper values (such as object fields).

static map_stream(source_stream, map_value)[source]#
Return type

AsyncIterable[~G]

wrap_field_resolver(base)[source]#

Make sure your resolvers are compatible with the runtime.

For instance, this could be making sure that non coroutine functions are executed inside a thread so blocking I/O doesn’t block the event loop.

This is specific to both the runtime and a caller resolver implementations and should be overriden liberally to suit the use case.

Return type

Callable[…, Any]

class py_gql.execution.BlockingExecutor(schema, document, variables, context_value, default_resolver=None, middlewares=None, instrumentation=None, disable_introspection=False, **_)[source]#

Executor implementation optimised for synchronous, blocking execution.

Warning

This is aimed to be used internally to optimised the blocking execution case while keeping the base Executor class as generic as possible by side-stepping some of the checks and lifts that need to happen when working with wrapping type such as Awaitable. It overrides much more of the base class than should be necessary to implement custom executors and should not be taken as an example.

supports_subscriptions = False#
execute_fields(parent_type, root, path, fields)[source]#
Return type

Dict[str, Any]

execute_fields_serially(parent_type, root, path, fields)#
Return type

Dict[str, Any]

resolve_field(parent_type, parent_value, field_definition, nodes, path)[source]#
Return type

Any

complete_list_value(inner_type, nodes, path, info, resolved_value)[source]#
Return type

List[Any]

complete_non_nullable_value(inner_type, nodes, path, info, resolved_value)[source]#
Return type

Any

py_gql.execution.default_resolver(root, context, info, __isinstance=<built-in function isinstance>, __getattr=<built-in function getattr>, __callable=<built-in function callable>, __mapping_cls=<class 'collections.abc.Mapping'>, **args)[source]#

Default resolver used during query execution.

This resolver looks up the value from the root in the following lookup order:

  • If root is a dict subcass:

    • If the field name is present and non callable, return it

    • If the field name is present and callable, return the result of

      calling it passing in (context, info, **args).

  • If root has an attribute corresponding to the field name:

    • If the attribute is non callable, return it

    • If the attribute is callable, treat it like a method and return the

      result of calling it passing in (context, info, **args).

  • Return None.

Parameters
  • root (Any) – Value of the resolved parent node.

  • context (Any) – User provided context value.

  • info (py_gql.execution.ResolveInfo) – Resolution context.

  • **args – Coerced field arguments.

Return type

Any

Returns

Resolved value.

py_gql.execution.execute(schema, document, *, operation_name=None, variables=None, initial_value=None, context_value=None, default_resolver=None, middlewares=None, instrumentation=None, disable_introspection=False, executor_cls=<class 'py_gql.execution.executor.Executor'>, executor_args=None)[source]#

Execute a GraphQL query or mutation against a schema.

Parameters
  • schema (Schema) – Schema to execute the query against

  • document (Document) – The query document

  • variables (Optional[Mapping[str, Any]]) – Raw, JSON decoded variables parsed from the request

  • operation_name (Optional[str]) – Operation to execute If specified, the operation with the given name will be executed. If not, this executes the single operation without disambiguation.

  • initial_value (Optional[Any]) – Root resolution value passed to top-level resolver

  • context_value (Optional[Any]) – Custom application-specific execution context. Use this to pass in anything your resolvers require like database connection, user information, etc. Limits on the type(s) used here will depend on your own resolver implementations and the executor class you use. Most thread safe data-structures should work.

  • default_resolver (Optional[Callable[…, Any]]) – Alternative default resolver. For field which do not specify a resolver, this will be used instead of py_gql.execution.default_resolver.

  • middlewares (Optional[Sequence[Callable[…, Any]]]) – List of middleware functions. Middlewares are used to wrap the resolution of all fields with common logic, they are good canidates for logging, authentication, and execution guards.

  • instrumentation (Optional[Instrumentation]) – Instrumentation instance. Use MultiInstrumentation to compose mutiple instances together.

  • disable_introspection (bool) – Use this to prevent schema introspection. This can be useful when you want to hide your full schema while keeping your API available. Note that this deviates the GraphQL specification and will likely break some clients so use this with caution.

  • executor_cls (Type[Executor]) –

    Executor class to use. Must be a subclass of py_gql.execution.Executor.

    This defines how your resolvers are going to be executed and the type of values you’ll get out of this function. executor_args will be passed on class instantiation as keyword arguments.

  • executor_args (Optional[Mapping[str, Any]]) – Extra executor arguments.

Return type

Any

Returns

Execution result.

Warning

The returned value will depend on the executor class. They ususually return a type wrapping the GraphQLResult object such as Awaitable[GraphQLResult]. You can refer to graphql_async or graphql_blocking for example usage.

class py_gql.execution.Executor(schema, document, variables, context_value, default_resolver=None, middlewares=None, instrumentation=None, disable_introspection=False, **_)[source]#

Core executor class.

This is the core executor class implementing all of the operations necessary to fulfill a GraphQL query or mutation.

By default, this executor assumes resolver are blocking and isn’t particularly optimised but provides various hooks to implement custom executors that back on different runtime. py_gql.execution.BlockingExecutor, py_gql.execution.AsyncIOExecutor and py_gql.execution.ThreadPoolExecutor are provided by default and optimised for their respective runtimes and can serve as a base for implementing such custom executors.

This implementation and the available override hooks assumes that most runtime can be supported by handling values wrapped in a _container type_ (such as a coroutine or a Future) and orchestrating the various relevant callbacks correctly. As such, most of the semantics will be described in these term and draw parallel to standard asyncio concepts.

supports_subscriptions = False#

Sentinel value indicating supports for subscription semantics.

static ensure_wrapped(value)[source]#

Ensure values are wrapped in the necessary container type.

This is essentially used after execution has finished to make sure the final value conforms to the expected types (e.g. coroutines) and avoid consumers having to typecheck them needlessly.

Return type

Any

static gather_values(values)[source]#

Group multiple wrapped values inside a single wrapped value.

This is equivalent to the asyncio.gather semantics.

Return type

Any

static map_value(value, then, else_=None)[source]#

Execute a callback on a wrapped value, potentially catching exceptions.

This is used internally to orchestrate callbacks and should be treated similarly to await semantics the map in Future combinators.

Return type

Any

static unwrap_value(value)[source]#

Recursively traverse wrapped values.

Given that resolution across the graph can span multiple level, this is used to support resolved values depending on deeper values (such as object fields).

static map_stream(source_stream, map_value)[source]#
Return type

Any

wrap_field_resolver(resolver)[source]#

Make sure your resolvers are compatible with the runtime.

For instance, this could be making sure that non coroutine functions are executed inside a thread so blocking I/O doesn’t block the event loop.

This is specific to both the runtime and a caller resolver implementations and should be overriden liberally to suit the use case.

Return type

Callable[…, Any]

add_error(err, path=None, node=None)[source]#
Return type

None

property errors#

All field errors collected during query execution.

Return type

List[GraphQLResponseError]

clear_errors()[source]#

Clear any collected error from the current executor instance.

Return type

None

does_fragment_type_apply(object_type, fragment)[source]#

Determine if a fragment is applicable to the given type.

Return type

bool

collect_fields(parent_type, selections, visited_fragments=None)[source]#

Collect all fields in a selection set, recursively traversing fragments in one single map and conserving definitino order.

Return type

Dict[str, List[Field]]

field_definition(parent_type, name)[source]#
Return type

Optional[Field]

argument_values(field_definition, node)[source]#
Return type

Dict[str, Any]

resolve_type(value, info, abstract_type)[source]#
Return type

Optional[ObjectType]

resolve_field(parent_type, parent_value, field_definition, nodes, path)[source]#
Return type

Any

execute_fields(parent_type, root, path, fields)[source]#
Return type

Any

execute_fields_serially(parent_type, root, path, fields)[source]#
Return type

Any

complete_list_value(inner_type, nodes, path, info, resolved_value)[source]#
Return type

Any

complete_non_nullable_value(inner_type, nodes, path, info, resolved_value)[source]#
Return type

Any

complete_value(field_type, nodes, path, info, resolved_value)[source]#
Return type

Any

py_gql.execution.get_operation(document, operation_name=None)[source]#

Extract relevant operation from a parsed document.

In case the operation_name argument is null, the document is expected to contain only one operation which will be extracted.

Parameters
  • document (Document) – Parsed document

  • opeation_name – Operation to extract

Returns: Relevant operation definition

Raises

InvalidOperationError – No relevant operation can be found.

Return type

OperationDefinition

class py_gql.execution.Instrumentation[source]#

Instrumentation provides a pattern to hook into and customise the GraphQL execution process.

Instrumentation objects provide two types of hooks:

  • on_* hooks which do not modify runtime values and are used to wrap execution stages. These hooks return a callback which will be called once the corresponding stage has finished.

  • instrument_* hooks which modify runtime values in between execution stages.

on_query()[source]#

This will be called at the very start of query processing.

The returned callback will be called immediatly before the execution result is returned to the caller.

Return type

Callable[[], None]

on_parse()[source]#

This will be called just before the request document is parsed. It will not be called when the execution code is provided an already parsed ast.

The returned callback will be called immediatly after the document has been parsed wether parsing was successful or not.

Return type

Callable[[], None]

on_validate()[source]#

This will be called before query validation.

The returned callback will be called immediatly after the document has been validated wether parsing was successful or not.

Return type

Callable[[], None]

on_execution()[source]#

This will be called before operation execution starts.

The returned callback will be called after operation execution ends.

Return type

Callable[[], None]

on_field(root, context, info)[source]#

This will be called before field execution starts.

The returned callback will be called after field execution ends and before field completion starts.

Return type

Callable[[], None]

instrument_ast(ast)[source]#

This will be called immediatly after the ast has been parsed. You should use this stage to apply any necessary transforms to the ast, such as field renaming or filtering.

Any GraphQLResponseError raised here will interrupt execution and be included in the response.

Return type

Document

instrument_validation_result(result)[source]#

This will be called after validation in allows you to transform the validation result before the decision is taken to interrupt query processing, e.g. by filtering out some errors.

Return type

ValidationResult

instrument_result(result)[source]#

This will be called just before the result is returned to the client. You should use this stage to apply any necessary transforms to the returned data.

Any ExecutionError raised here will interrupt execution and be included in the response.

Return type

GraphQLResult

class py_gql.execution.MultiInstrumentation(*instrumentations)[source]#

Support for specifying multiple Instrumentation instances at a time.

Instrumentations will be processed as a stack: instrument_* and on_* hooks will be called in order while the callbacks will be called in reverse order

on_query()[source]#

This will be called at the very start of query processing.

The returned callback will be called immediatly before the execution result is returned to the caller.

Return type

Callable[[], None]

on_parse()[source]#

This will be called just before the request document is parsed. It will not be called when the execution code is provided an already parsed ast.

The returned callback will be called immediatly after the document has been parsed wether parsing was successful or not.

Return type

Callable[[], None]

on_validate()[source]#

This will be called before query validation.

The returned callback will be called immediatly after the document has been validated wether parsing was successful or not.

Return type

Callable[[], None]

on_execution()[source]#

This will be called before operation execution starts.

The returned callback will be called after operation execution ends.

on_field(root, context, info)[source]#

This will be called before field execution starts.

The returned callback will be called after field execution ends and before field completion starts.

Return type

Callable[[], None]

instrument_ast(ast)[source]#

This will be called immediatly after the ast has been parsed. You should use this stage to apply any necessary transforms to the ast, such as field renaming or filtering.

Any GraphQLResponseError raised here will interrupt execution and be included in the response.

Return type

Document

instrument_validation_result(result)[source]#

This will be called after validation in allows you to transform the validation result before the decision is taken to interrupt query processing, e.g. by filtering out some errors.

Return type

ValidationResult

instrument_result(result)[source]#

This will be called just before the result is returned to the client. You should use this stage to apply any necessary transforms to the returned data.

Any ExecutionError raised here will interrupt execution and be included in the response.

Return type

GraphQLResult

py_gql.execution.subscribe(schema, document, *, operation_name=None, variables=None, initial_value=None, context_value=None, instrumentation=None, executor_cls=<class 'py_gql.execution.executor.Executor'>, executor_args=None)[source]#

Execute a GraphQL subscription against a schema and return the appropriate response stream. This assumes the query has been validated beforehand.

Parameters
  • schema (Schema) – Schema to execute the query against

  • document (Document) – The query document

  • variables (Optional[Mapping[str, Any]]) – Raw, JSON decoded variables parsed from the request

  • operation_name (Optional[str]) – Operation to execute If specified, the operation with the given name will be executed. If not, this executes the single operation without disambiguation.

  • initial_value (Optional[Any]) – Root resolution value passed to top-level resolver

  • context_value (Optional[Any]) – Custom application-specific execution context. Use this to pass in anything your resolvers require like database connection, user information, etc. Limits on the type(s) used here will depend on your own resolver implementations and the executor class you use. Most thread safe data-structures should work.

  • tracer – Tracer instance.

  • executor_cls (Type[Executor]) –

    Executor class to use. Must be a subclass of py_gql.execution.Executor.

    This defines how your resolvers are going to be executed and the type of values you’ll get out of this function. executor_args will be passed on class instantiation as keyword arguments.

  • executor_args (Optional[Mapping[str, Any]]) – Extra executor arguments.

Return type

Any

Returns

An iterator over subscription results.

Warning

The returned value will depend on the executor class. They ususually return a type wrapping the GraphQLResult object such as Awaitable[GraphQLResult]. You can refer to graphql_async or graphql_blocking for example usage.

class py_gql.execution.ThreadPoolExecutor(*args, inner_executor=None, **kwargs)[source]#
static ensure_wrapped(value)[source]#

Ensure values are wrapped in the necessary container type.

This is essentially used after execution has finished to make sure the final value conforms to the expected types (e.g. coroutines) and avoid consumers having to typecheck them needlessly.

static map_value(value, then, else_=None)[source]#

Execute a callback on a wrapped value, potentially catching exceptions.

This is used internally to orchestrate callbacks and should be treated similarly to await semantics the map in Future combinators.

static gather_values(values)[source]#

Group multiple wrapped values inside a single wrapped value.

This is equivalent to the asyncio.gather semantics.

static unwrap_value(value)[source]#

Recursively traverse wrapped values.

Given that resolution across the graph can span multiple level, this is used to support resolved values depending on deeper values (such as object fields).

wrap_field_resolver(resolver)[source]#

Make sure your resolvers are compatible with the runtime.

For instance, this could be making sure that non coroutine functions are executed inside a thread so blocking I/O doesn’t block the event loop.

This is specific to both the runtime and a caller resolver implementations and should be overriden liberally to suit the use case.

Return type

Callable[…, Any]

class py_gql.execution.GraphQLExtension[source]#

Encode a GraphQL response extension.

Use in conjonction with GraphQLResult.add_extension() to encode the response alongside an execution result.

payload()[source]#
Returns

Extension payload; must be JSON serialisable.

Return type

Any

property name#

Returns: Name of the extension used as the key in the response.

Return type

str

class py_gql.execution.GraphQLResult(data=<object object>, errors=None)[source]#

Wrapper encoding the behaviour described in the Response part of the specification.

Parameters
  • data (Optional[Dict[str, Any]]) – The data part of the response.

  • errors (Optional[Sequence[GraphQLResponseError]]) – The errors part of the response. All errors will be included in the response using to_dict().

data#
errors#
extensions#
add_extension(ext)[source]#

Add an extensions to the result.

Parameters

instance (Extension) –

Raises

ValueError – Extension with the same name has already been added

response()[source]#

Generate an ordered response dict.

Return type

Dict[str, Any]

json(**kw)[source]#

Encode response as JSON using the standard lib json module.

Parameters

**kw – Keyword args passed to to json.dumps

Return type

str

class py_gql.execution.ResolveInfo(field_definition, path, parent_type, schema, variables, fragments, nodes)[source]#
field_definition#
path#
parent_type#
schema#
variables#
fragments#
nodes#