apollo-upload-client和graphene-django

问题描述 投票:2回答:2

我有一个关于使用apollo-upload-clientgraphene-django的问题。 Here我发现apollo-upload-clientoperations添加到formData。但here graphene-django只是试图获得query参数。问题是,应该在何处以及如何解决这个问题?

file-upload apollo-client graphene-python
2个回答
1
投票

如果您指的是具有标题的数据(从Chrome工具查看HTTP时):

Content-Disposition: form-data; name="operations"

和数据一样

{"operationName":"MyMutation","variables":{"myData"....}, "query":"mutation MyMutation"...}

graphene-python库解释这个并将它组装成一个查询,插入变量并从查询中删除文件数据。如果您使用的是Django,则可以在编写变异时在info.context.FILES中找到所有上传的文件。


0
投票

这是我的解决方案,以支持最新的apollo-upload-client(8.1)。当我从apollo-upload-client 5.x升级到8.x时,我最近不得不重新访问我的Django代码。希望这可以帮助。

对不起,我使用的是较旧的graphene-django,但希望您可以将变异语法更新到最新版本。

上传标量类型(passthrough,基本上):

class Upload(Scalar):
    '''A file upload'''

    @staticmethod
    def serialize(value):
        raise Exception('File upload cannot be serialized')

    @staticmethod
    def parse_literal(node):
        raise Exception('No such thing as a file upload literal')

    @staticmethod
    def parse_value(value):
        return value

我的上传突变:

class UploadImage(relay.ClientIDMutation):
    class Input:
        image = graphene.Field(Upload, required=True)

    success = graphene.Field(graphene.Boolean)

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        with NamedTemporaryFile(delete=False) as tmp:
            for chunk in input['image'].chunks():
                tmp.write(chunk)
            image_file = tmp.name
        # do something with image_file
        return UploadImage(success=True)

繁重的工作发生在自定义GraphQL视图中。基本上它将文件对象注入变量映射中的适当位置。

def maybe_int(s):
    try:
        return int(s)
    except ValueError:
        return s

class CustomGraphqlView(GraphQLView):
    def parse_request_json(self, json_string):
        try:
            request_json = json.loads(json_string)
            if self.batch:
                assert isinstance(request_json,
                                  list), ('Batch requests should receive a list, but received {}.').format(
                                      repr(request_json))
                assert len(request_json) > 0, ('Received an empty list in the batch request.')
            else:
                assert isinstance(request_json, dict), ('The received data is not a valid JSON query.')
            return request_json
        except AssertionError as e:
            raise HttpError(HttpResponseBadRequest(str(e)))
        except BaseException:
            logger.exception('Invalid JSON')
            raise HttpError(HttpResponseBadRequest('POST body sent invalid JSON.'))

    def parse_body(self, request):
        content_type = self.get_content_type(request)

        if content_type == 'application/graphql':
            return {'query': request.body.decode()}

        elif content_type == 'application/json':
            return self.parse_request_json(request.body.decode('utf-8'))
        elif content_type in ['application/x-www-form-urlencoded', 'multipart/form-data']:
            operations_json = request.POST.get('operations')
            map_json = request.POST.get('map')
            if operations_json and map_json:
                operations = self.parse_request_json(operations_json)
                map = self.parse_request_json(map_json)
                for file_id, f in request.FILES.items():
                    for name in map[file_id]:
                        segments = [maybe_int(s) for s in name.split('.')]
                        cur = operations
                        while len(segments) > 1:
                            cur = cur[segments.pop(0)]
                        cur[segments.pop(0)] = f
                logger.info('parse_body %s', operations)
                return operations
            else:
                return request.POST

        return {}
© www.soinside.com 2019 - 2024. All rights reserved.