Graphene File Upload

1.3.0 · active · verified Thu Apr 16

graphene-file-upload is a Python library that extends Graphene, Graphene-Django, and Flask-GraphQL to enable robust file upload functionality in GraphQL mutations. It acts as a drop-in replacement for the standard GraphQL view and adheres to the GraphQL Multipart Request Specification. The current version is 1.3.0, with releases occurring periodically but not on a fixed cadence, the last significant update being in early 2021.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a GraphQL mutation that accepts a file upload using the `Upload` scalar. The `mutate` method receives the uploaded file object (e.g., `InMemoryUploadedFile` in Django). It then shows how to integrate this into a Django `urls.py` or Flask `app.py` by using `FileUploadGraphQLView` instead of the standard GraphQL view. The example includes basic file saving to a local 'uploads' directory.

import graphene
from graphene_file_upload.scalars import Upload
from graphene_file_upload.django import FileUploadGraphQLView

import os # For example file handling

class UploadFileMutation(graphene.Mutation):
    class Arguments:
        file = Upload(required=True)

    success = graphene.Boolean()
    file_name = graphene.String()
    file_size = graphene.Int()

    def mutate(self, info, file, **kwargs):
        # `file` is a Django InMemoryUploadedFile or TemporaryUploadedFile object
        # `info.context.FILES` also contains the uploaded files
        
        # Example: Save the file to a temporary location or process it
        upload_dir = 'uploads'
        os.makedirs(upload_dir, exist_ok=True)
        file_path = os.path.join(upload_dir, file.name)
        with open(file_path, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        return UploadFileMutation(
            success=True,
            file_name=file.name,
            file_size=file.size
        )

class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="stranger"))

    def resolve_hello(self, info, name):
        return "Hello " + name

class Mutation(graphene.ObjectType):
    upload_file = UploadFileMutation.Field()

schema = graphene.Schema(query=Query, mutation=Mutation)

# --- Django urls.py example (assuming you have a Django project setup) ---
# from django.urls import path
# from .schema import schema
#
# urlpatterns = [
#     path(
#         'graphql/',
#         FileUploadGraphQLView.as_view(schema=schema, graphiql=True)
#     ),
# ]
#
# --- Flask app.py example (assuming you have a Flask app setup) ---
# from flask import Flask
# from .schema import schema # assuming schema is in a schema.py file
#
# app = Flask(__name__)
# app.add_url_rule(
#     '/graphql',
#     view_func=FileUploadGraphQLView.as_view(schema=schema, graphiql=True)
# )

view raw JSON →