File upload 阿波罗上传客户端和graphene django
我有一个关于使用apollo上传客户端和graphene django的问题。我发现apollo upload客户端向formData添加操作。但graphene django只是试图获取查询参数。问题是,应该在何处以及如何修复它?如果您所指的数据具有类似于从Chrome工具查看HTTP时的标题: 内容配置:表单数据;名称=操作 和数据一样 {operationName:MyMutation,变量:{myData..},查询:mutation-MyMutation..}File upload 阿波罗上传客户端和graphene django,file-upload,apollo-client,graphene-python,File Upload,Apollo Client,Graphene Python,我有一个关于使用apollo上传客户端和graphene django的问题。我发现apollo upload客户端向formData添加操作。但graphene django只是试图获取查询参数。问题是,应该在何处以及如何修复它?如果您所指的数据具有类似于从Chrome工具查看HTTP时的标题: 内容配置:表单数据;名称=操作 和数据一样 {operationName:MyMutation,变量:{myData..},查询:mutation-MyMutation..} graphenepyth
graphenepython库对此进行解释,并将其组装到查询中,插入变量并从查询中删除文件数据。如果您使用的是Django,那么在编写变体时,您可以在info.context.files中找到所有上载的文件。以下是我支持最新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 {}