Skip to main content

graphql-sync-dataloaders

Use DataLoaders in your Python GraphQL servers that have to run in a sync context (i.e. Django).

Requirements

  • Python 3.8+
  • graphql-core >=3.2.0

Installation

This package can be installed from PyPi by running:

pip install graphql-sync-dataloaders

Strawberry setup

When creating your Strawberry Schema pass DeferredExecutionContext as the execution_context_class argument:

# schema.py
import strawberry
from graphql_sync_dataloaders import DeferredExecutionContext

schema = strawberry.Schema(Query, execution_context_class=DeferredExecutionContext)

Then create your dataloaders using the SyncDataLoader class:

from typing import List

from graphql_sync_dataloaders import SyncDataLoader

from .app import models  # your Django models

def load_users(keys: List[int]) -> List[User]:
    qs = models.User.objects.filter(id__in=keys)
    user_map = {user.id: user for user in qs}
    return [user_map.get(key, None) for key in keys]

user_loader = SyncDataLoader(load_users)

You can then use the loader in your resolvers and it will automatically be batched to reduce the number of SQL queries:

import strawberry

@strawberry.type
class Query:
    @strawberry.field
    def get_user(self, id: strawberry.ID) -> User:
        return user_loader.load(id)

Note: You probably want to setup your loaders in context. See https://strawberry.rocks/docs/guides/dataloaders#usage-with-context for more details

The following query will only make 1 SQL query:

fragment UserDetails on User {
  username
}

query {
  user1: getUser(id: '1') {
    ...UserDetails
  }
  user2: getUser(id: '2') {
    ...UserDetails
  }
  user3: getUser(id: '3') {
    ...UserDetails
  }
}

Graphene-Django setup

Requires graphene-django >=3.0.0b8

When setting up your GraphQLView pass DeferredExecutionContext as the execution_context_class argument:

# urls.py
from django.urls import path
from graphene_django.views import GraphQLView
from graphql_sync_dataloaders import DeferredExecutionContext

from .schema import schema

urlpatterns = [
    path(
        "graphql",
        csrf_exempt(
            GraphQLView.as_view(
                schema=schema, 
                execution_context_class=DeferredExecutionContext
            )
        ),
    ),
]

Then create your dataloaders using the SyncDataLoader class:

from typing import List

from graphql_sync_dataloaders import SyncDataLoader

from .app import models  # your Django models

def load_users(keys: List[int]) -> List[User]:
    qs = models.User.objects.filter(id__in=keys)
    user_map = {user.id: user for user in qs}
    return [user_map.get(key, None) for key in keys]

user_loader = SyncDataLoader(load_users)

You can then use the loader in your resolvers and it will automatically be batched to reduce the number of SQL queries:

import graphene

class Query(graphene.ObjectType):
    get_user = graphene.Field(User, id=graphene.ID)

    def resolve_get_user(root, info, id):
        return user_loader.load(id)

The following query will only make 1 SQL query:

fragment UserDetails on User {
  username
}

query {
  user1: getUser(id: '1') {
    ...UserDetails
  }
  user2: getUser(id: '2') {
    ...UserDetails
  }
  user3: getUser(id: '3') {
    ...UserDetails
  }
}

How it works

This library implements a custom version of the graphql-core ExecutionContext class that is aware of the SyncFuture objects defined in this library. A SyncFuture represents a value that hasn't been resolved to a value yet (similiar to asycnio Futures or JavaScript Promises) and that is what the SyncDataLoader returns when you call the .load function.

When the custom ExecutionContext encounters a SyncFuture that gets returned from a resolver and it keeps track of them. Then after the first pass of the exection it triggers the SyncFuture callbacks until there are none left. Once there are none left the data is fully resolved and can be returned to the caller synchronously. This allows us to implement a DataLoader pattern that batches calls to a loader function, and it allows us to do this in a fully synchronously way.

Credits

@Cito for graphql-core and for implementing the first version of this in https://github.com/graphql-python/graphql-core/pull/155

Metadata

Release files for graphql-sync-dataloaders 0.1.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 graphql-sync-dataloaders 0.1.1
File Size Uploaded
graphql-sync-dataloaders-0.1.1.tar.gz 8.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for graphql-sync-dataloaders 0.1.1
File Interpreter ABI Platform
graphql_sync_dataloaders-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 16.7 kB

Release files / graphql-sync-dataloaders-0.1.1.tar.gz

Download URL graphql-sync-dataloaders-0.1.1.tar.gz
Size 8.6 kB
Tags Source
SHA-256 checksum
How to use checksums
67c708e89c46b401188b773af055850278e4e1d5af2f66bf31d9bd0d504d95b9
BLAKE2b-256 checksum
How to use checksums
01ba329bda79f7876804d03da659f9b6317ff30f34a1a93c3f4b097f4038d618
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.1 CPython/3.10.2 Linux/5.15.0-1020-azure

Release files / graphql_sync_dataloaders-0.1.1-py3-none-any.whl

Download URL graphql_sync_dataloaders-0.1.1-py3-none-any.whl
Size 8.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f003f1184417acf156b2f73c4f0e76487514a455143a22ab796c110db4bc4693
BLAKE2b-256 checksum
How to use checksums
aa045176bd5dabb56f835ed80ba2367e190575b3c9f8015f8d2ce9058a9a4fab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.1 CPython/3.10.2 Linux/5.15.0-1020-azure

Release history Release notifications | RSS feed

This release

0.1.1 This release

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