Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upload file #1529

Open
zamaniramin549 opened this issue Nov 21, 2023 · 2 comments
Open

Upload file #1529

zamaniramin549 opened this issue Nov 21, 2023 · 2 comments

Comments

@zamaniramin549
Copy link

I'm currently attempting to upload files using Graphene and have explored several packages in my search. Unfortunately, none of them have proven effective. It seems to be a notable issue that Graphene lacks built-in support for file uploads.

@erikwrede
Copy link
Member

Graphene does support file uploads, but it's a matter of the underlying web view (for example graphene Django, starlette-graphene3, GraphQL-server) to support them. What's your stack? If you're able to provide a minimal example I might be able to help.

@sdobbelaere
Copy link

sdobbelaere commented Nov 23, 2023

In reality if you google this topic extensively, you'll notice that there are a number of ways to tackle it.
In the example below, the path we've chosen is to stick to graphql only and used graphene-file-upload.

That graphene-file-upload package supports file transfers. By now, it seems that it hasn't received any updates in a couple of years. But if something would break, I can imagine it will be easy enough to fork and fix.

This very minimal example below is how I tackled the mutation a couple of years ago with that package. It's not intended to work out of the box, it's just a simplified snippet from a codebase in one of our projects at Tweave.tech

from graphene_file_upload.scalars import Upload
import graphene
from .validators import your_file_validator

class CreateFile(graphene.Mutation):
    file = graphene.Field(FileType, required=False)

    class Arguments:
        filename = graphene.String(required=True)
        filecontents = Upload(required=True)

    @staticmethod
    def mutate(root, info, filename, filecontents, *args, **kwargs):
        user = info.context.user
        file_instance = File()
        file_instance.file.save(filename, ContentFile(filecontents.file.read()), save=False)

        try:
            your_file_validator(file_instance.file)
            file_instance.save()
            return CreateFile(file=file_instance)
        except ValidationError:
            return CreateFile(file=None)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants