Skip to main content

Graphene Directives

Schema Directives implementation for graphene

PyPI version PyPI pyversions Downloads Test Status Coverage Status


Directive Locations Supported

  • DirectiveLocation.SCHEMA
  • DirectiveLocation.OBJECT
  • DirectiveLocation.ENUM
  • DirectiveLocation.INTERFACE
  • DirectiveLocation.UNION
  • DirectiveLocation.SCALAR
  • DirectiveLocation.FIELD_DEFINITION
  • DirectiveLocation.INPUT_FIELD_DEFINITION
  • DirectiveLocation.INPUT_OBJECT
  • DirectiveLocation.ENUM_VALUE
  • DirectiveLocation.ARGUMENT_DEFINITION,

Example

Using @directive

import graphene
from graphql import GraphQLArgument, GraphQLInt, GraphQLNonNull, GraphQLString

from graphene_directives import (
    CustomDirective,
    DirectiveLocation,
    build_schema,
    directive,
)

CacheDirective = CustomDirective(
    name="cache",
    locations=[DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.OBJECT],
    args={
        "max_age": GraphQLArgument(
            GraphQLNonNull(GraphQLInt),
            description="Specifies the maximum age for cache in seconds.",
        ),
        "swr": GraphQLArgument(
            GraphQLInt, description="Stale-while-revalidate value in seconds. Optional."
        ),
        "scope": GraphQLArgument(
            GraphQLString, description="Scope of the cache. Optional."
        ),
    },
    description="Caching directive to control cache behavior of fields or fragments.",
)


@directive(CacheDirective, max_age=200)
class SomeType(graphene.ObjectType):
    field_1 = directive(CacheDirective, field=graphene.String(), max_age=300)
    field_2 = directive(CacheDirective, field=graphene.String(), max_age=300, swr=2)
    field_3 = graphene.String()


class Query(graphene.ObjectType):
    some_query = graphene.Field(SomeType)


schema = build_schema(query=Query, directives=[CacheDirective])

Using directive_decorator

import graphene
from graphql import GraphQLArgument, GraphQLInt, GraphQLNonNull, GraphQLString

from graphene_directives import (
    CustomDirective,
    DirectiveLocation,
    build_schema,
    directive_decorator,
)

CacheDirective = CustomDirective(
    name="cache",
    locations=[DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.OBJECT],
    args={
        "max_age": GraphQLArgument(
            GraphQLNonNull(GraphQLInt),
            description="Specifies the maximum age for cache in seconds.",
        ),
        "swr": GraphQLArgument(
            GraphQLInt, description="Stale-while-revalidate value in seconds. Optional."
        ),
        "scope": GraphQLArgument(
            GraphQLString, description="Scope of the cache. Optional."
        ),
    },
    description="Caching directive to control cache behavior of fields or fragments.",
)

# This returns a partial of directive function
cache = directive_decorator(target_directive=CacheDirective)


@cache(max_age=200)
class SomeType(graphene.ObjectType):
    field_1 = cache(field=graphene.String(), max_age=300)
    field_2 = cache(field=graphene.String(), max_age=300, swr=2)
    field_3 = graphene.String()


class Query(graphene.ObjectType):
    some_query = graphene.Field(SomeType)


schema = build_schema(query=Query, directives=[CacheDirective])

Custom Input Validation

from typing import Any

import graphene
from graphql import GraphQLArgument, GraphQLInt, GraphQLNonNull, GraphQLString

from graphene_directives import (
    CustomDirective,
    DirectiveLocation,
    Schema,
    build_schema,
    directive_decorator,
)


def input_transform(inputs: dict, _schema: Schema) -> dict:
    """
    def input_transform (inputs: Any, schema: Schema) -> dict,
    """
    if inputs.get("max_age") > 200:
        inputs["swr"] = 30
    return inputs


def validate_non_field_input(_type: Any, inputs: dict, _schema: Schema) -> bool:
    """
    def validator (type_: graphene type, inputs: Any, schema: Schema) -> bool,
    if validator returns False, library raises DirectiveCustomValidationError
    """
    if inputs.get("max_age") > 2500:
        return False
    return True


def validate_field_input(
    _parent_type: Any, _field_type: Any, inputs: dict, _schema: Schema
) -> bool:
    """
    def validator (parent_type_: graphene_type, field_type_: graphene type, inputs: Any, schema: Schema) -> bool,
    if validator returns False, library raises DirectiveCustomValidationError
    """
    if inputs.get("max_age") > 2500:
        return False
    return True


CacheDirective = CustomDirective(
    name="cache",
    locations=[DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.OBJECT],
    args={
        "max_age": GraphQLArgument(
            GraphQLNonNull(GraphQLInt),
            description="Specifies the maximum age for cache in seconds.",
        ),
        "swr": GraphQLArgument(
            GraphQLInt, description="Stale-while-revalidate value in seconds. Optional."
        ),
        "scope": GraphQLArgument(
            GraphQLString, description="Scope of the cache. Optional."
        ),
    },
    description="Caching directive to control cache behavior of fields or fragments.",
    non_field_validator=validate_non_field_input,
    field_validator=validate_field_input,
    input_transform=input_transform,
)

# This returns a partial of directive function
cache = directive_decorator(target_directive=CacheDirective)


@cache(max_age=200)
class SomeType(graphene.ObjectType):
    field_1 = cache(field=graphene.String(), max_age=300)
    field_2 = cache(field=graphene.String(), max_age=300, swr=2)
    field_3 = graphene.String()


class Query(graphene.ObjectType):
    some_query = graphene.Field(SomeType)


schema = build_schema(query=Query, directives=[CacheDirective])

Complex Use Cases

Refer Code and Graphql Output

Release files for graphene-directives 0.5.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for graphene-directives 0.5.1
File Size Uploaded
graphene_directives-0.5.1.tar.gz 13.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for graphene-directives 0.5.1
File Interpreter ABI Platform
graphene_directives-0.5.1-py3-none-any.whl Python 3 none any Details

Total release size:31.0 kB

Release files / graphene_directives-0.5.1.tar.gz

Download URL graphene_directives-0.5.1.tar.gz
Size 13.9 kB
Tags Source
SHA-256 checksum
How to use checksums
f3bdf15d3f624174f3994ee268a5e3fe593250c01dd3b57f9c8e4d164b79535d
BLAKE2b-256 checksum
How to use checksums
6f204d3c1a45c1528336905065b44383d3858770d2ed1a373422edaade51daa7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.4.1 CPython/3.14.6 Linux/6.17.0-1020-azure

Release files / graphene_directives-0.5.1-py3-none-any.whl

Download URL graphene_directives-0.5.1-py3-none-any.whl
Size 17.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6af82d8387bf563dd249d92e64c0aff45297a8c4ff5a74069176b30593acf5f1
BLAKE2b-256 checksum
How to use checksums
31abff739dea6877204cd937e86c121514a6a78d0c44041fe48356bcaf61ec18
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.4.1 CPython/3.14.6 Linux/6.17.0-1020-azure

Release history Release notifications | RSS feed

This release

0.5.1 This release

2 release files

0.5.0

2 release files

0.4.8

2 release files

0.4.7

2 release files

0.4.6

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page