apollo-upload-client和graphene-django

时间:2018-02-09 20:51:53

标签: file-upload apollo-client graphene-python

我对使用apollo-upload-clientgraphene-django有疑问。 Here我发现apollo-upload-clientoperations添加到formData。但here graphene-django仅尝试获取query参数。问题是,应该在何处以及如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

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

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

之类的数据

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

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

答案 1 :(得分:0)

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

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

上传标量类型(基本上是直通):

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 {}