py_gql.execution#

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

Execute a query or mutation against a schema.

Warning

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 the 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 and the runtime implementations used. Most thread safe data-structures should work with built in runtimes.
  • 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 candidates for logging, authentication, and execution guards.
  • instrumentation (Optional[Instrumentation]) – Instrumentation instance. Use MultiInstrumentation to compose multiple 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 from the GraphQL specification and will likely break some clients (such as GraphiQL) so use this with caution.
  • runtime (Optional[Runtime]) – Runtime against which to execute field resolvers (defaults to ~py_gql.execution.runtime.BlockingRuntime()).
  • executor_cls (Type[Executor]) – Executor class to use. The executor class defines the implementation of the GraphQL resolution algorithm. This must be a subclass of py_gql.execution.Executor.
Return type:

Any

Returns:

Execution result. Exact type dependent on the runtime.

Raises:

RuntimeError – on invalid operation.

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

Execute a subscription against a schema and return the appropriate response stream.

Warning

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.
  • instrumentation (Optional[Instrumentation]) – Instrumentation instance. Use MultiInstrumentation to compose multiple instances together.
  • runtime (SubscriptionRuntime) – Runtime against which to execute field resolvers (defaults to ~py_gql.execution.runtime.BlockingRuntime()).
  • executor_cls (Type[Executor]) – Executor class to use. The executor class defines the implementation of the GraphQL resolution algorithm. This must be a subclass of py_gql.execution.Executor.
Return type:

Any

Returns:

An iterator over subscription results. Exact type dependent on the runtime.

Raises:

RuntimeError – on invalid operation.

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

Core executor class.

This is the core executor class implementing all of the operations necessary to fulfill a GraphQL query or mutation as defined [in the spec]( https://spec.graphql.org/June2018/#sec-Execution).

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
context_value#
document#
execute_fields(parent_type, root, path, fields)[source]#
Return type:Any
execute_fields_serially(parent_type, root, path, fields)[source]#
Return type:Any
field_resolver(parent_type, field_definition)[source]#
Return type:Callable[…, Any]
fragments#
instrumentation#
resolve_field(parent_type, parent_value, field_definition, nodes, path)[source]#
Return type:Any
resolve_type(value, info, abstract_type)[source]#
Return type:Optional[ObjectType]
runtime#
schema#
variables#
class py_gql.execution.GraphQLResult(data=<object object>, errors=None)[source]#

Operation response.

This wrapper encodes the behavior 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().
add_extension(ext)[source]#

Add an extensions to the result.

Parameters:ext – Extension instance
Raises:ValueError – Extension with the same name has already been added
data#
errors#
extensions#
json(**kw)[source]#

Encode response as JSON using the standard lib json module.

Parameters:**kw – Keyword args passed to to json.dumps
Returns:JSON serialized response.
Return type:str
response()[source]#

Generate an ordered response dict.

Return type:Dict[str, Any]
class py_gql.execution.GraphQLExtension[source]#

Encode a GraphQL response extension.

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

name#

Return the name of the extension used as the key in the response.

Return type:str
payload()[source]#

Return the extension payload.

Return type:Dict[str, Any]
class py_gql.execution.ResolveInfo(field_definition, path, parent_type, nodes, runtime, context)[source]#

Expose information about the field currently being resolved.

This is the 3rd positional argument provided to resolver functions and is constructed internally during query execution.

field_definition#

Root field being resolved.

Type:Field
fragments#

Document fragments.

Return type:Dict[str, FragmentDefinition]
get_directive_arguments(name)[source]#

Extract arguments for a given directive on the current field.

Warning

This method assumes the document has been validated and the definition exists and is valid at this position.

Parameters:name (str) – The name of the directive to extract.
Return type:Optional[Dict[str, Any]]
Returns:None if the directive is not present on the current field and a dictionary of coerced arguments otherwise.
nodes#

AST nodes extracted from the document.

Type:Field
parent_type#

Type from which the field is being resolved.

Type:ObjectType
path#

Current traversal path through the query.

Type:ResponsePath
runtime#

Current runtime.

Type:Runtime
schema#

Current schema.

Return type:Schema
selected_fields(*, maxdepth=1, pattern=None)[source]#

Extract the list of fields selected by the field currently being resolved.

Refer to selected_fields() for documentation.

Return type:List[str]
variables#

Coerced variables.

Return type:Dict[str, 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]#

Resolve a field from dictionaries or objects.

This is the default resolver used during query execution and looks up the value from the root in the following lookup order:

  • If root is a dict subclass:
    • If the field is present return it
  • 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.

If the field defined a custom python_name attribute, this will be used instead of the field name.

As this is can be called a lot during execution, the __* type arguments are there as an optimisation.

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.

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

Executor implementation optimized for synchronous, blocking execution.

Warning

This is aimed to be used internally to optimize the blocking execution case while keeping the base Executor class as generic as possible by side-stepping some of the operations that need to happen when working with arbitrary wrapper types such as Awaitable. As a result this overrides much more of the base class than should be necessary to implement custom executors and should not be taken as an example.

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
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
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
  • operation_name (Optional[str]) – Operation to extract
Return type:

OperationDefinition

Returns:

Relevant operation definition

Raises:

InvalidOperationError – No relevant operation can be found.

class py_gql.execution.Instrumentation[source]#

Observability hooks for the executor.

Instrumentation provides a pattern to hook into py_gql’s execution process for observability purposes.

on_execution_end()[source]#

This will be after operation execution ends and the execution result is ready.

Return type:None
on_execution_start()[source]#

This will be called before operation execution starts.

Return type:None
on_field_end(root, context, info)[source]#

This will be called after field resolution ends.

Return type:None
on_field_start(root, context, info)[source]#

This will be called before field resolution starts.

Return type:None
on_parsing_end()[source]#

This will be called after the request document has been parsed.

This is called even if parsing failed due to a syntax error.

Return type:None
on_parsing_start()[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.

Return type:None
on_query_end()[source]#

This will be called once the execution result is ready.

Return type:None
on_query_start()[source]#

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

Return type:None
on_validation_end()[source]#

This will be called before query validation.

Return type:None
on_validation_start()[source]#

This will be called before query validation.

Return type:None
class py_gql.execution.MultiInstrumentation(*instrumentations)[source]#

Combine multiple Instrumentation instances.

Instrumentations will be processed as a stack: on_start* hooks will be called in order while on_*_end hooks will be called in reverse order.

on_execution_end()[source]#

This will be after operation execution ends and the execution result is ready.

Return type:None
on_execution_start()[source]#

This will be called before operation execution starts.

Return type:None
on_field_end(root, context, info)[source]#

This will be called after field resolution ends.

Return type:None
on_field_start(root, context, info)[source]#

This will be called before field resolution starts.

Return type:None
on_parsing_end()[source]#

This will be called after the request document has been parsed.

This is called even if parsing failed due to a syntax error.

Return type:None
on_parsing_start()[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.

Return type:None
on_query_end()[source]#

This will be called once the execution result is ready.

Return type:None
on_query_start()[source]#

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

Return type:None
on_validation_end()[source]#

This will be called before query validation.

Return type:None
on_validation_start()[source]#

This will be called before query validation.

Return type:None