如何使用graphene-django上传和下载文件? [英] How can I upload and download files with graphene-django?

查看:107
本文介绍了如何使用graphene-django上传和下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前使用的是graphene-django v2.0,我对如何上传和下载图像等文件一无所知,有没有人举过一个查询示例,您可以在其中下载图像和变体,您可以上传一个?

I'm currently using graphene-django v2.0 and I've absolutely no clue of how can I upload and download files like images, does anyone have an example of a query where you can download an Image and a mutation where you can upload one?

推荐答案

上传

您无需发明自己的前端代码即可将文件上传添加到变异中-现有的软件包已在执行此操作。例如,如果您正在使用Apollo,则 apollo-upload-client

You don't need to invent your own frontend code to add a file upload to a mutation -- there are existing packages that do this already. For example, apollo-upload-client if you are using Apollo.

要在后端接收上传的文件,这些文件将在字典 request.FILES 中可用。因此,处理文件上传的任何变异都需要检查 info.context.FILES.items 来获取和保存文件数据。这段代码的细节将取决于保存文件的最终目标。

To receive an uploaded file on the backend, the files are going to be available in the dictionary request.FILES. So any mutation handling a file upload needs to examine info.context.FILES.items to get and save the file data. The specifics of this code are going to depend on the ultimate destination of the saved file.

(UPDATE)但是,如果可能的话,我建议使用graphene-django上传文件,因为它在后端和前端都增加了大量的复杂性。我的团队最终取消了我们的可工作的graphene-django文件上传代码,并将其替换为标准Django文件上传

(UPDATE) However, if possible I would recommend not using graphene-django to upload files because it adds a large amount of complexity on both the backend and the frontend. My team ultimately scrapped our working graphene-django file upload code and replaced it with a standard Django file upload.

下载

用于下载,我建议使用graphQL进行实际下载。而是创建一个Django函数视图,该视图返回 HttpResponse FileResponse 并设置Content-Disposition标头。

For downloads, I would recommend not using graphQL for the actual download. Instead create a Django function view that returns a HttpResponse or FileResponse and sets the Content-Disposition header. Something like

from django.http import HttpResponse

def download(request):
    ... do stuff to get file contents and file name and mime_type
    response = HttpResponse(file_contents, content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)
    return response

然后添加此文件您的 urls.py 和graphQL查询响应的下载路径。因此,可以使用graphQL来获取下载路径,但实际上下载文件将是常规的Django页面。

Then add this download path to your urls.py and to a graphQL query response. So graphQL would be used to get the download path, but actually downloading the file would be a regular Django page.

这篇关于如何使用graphene-django上传和下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆